Scope Javascript

Confused Pirate

How do you explain scope. C’mon man It’s like scope, you know. Try to explain scope

Wikipedia has a good explanation.

OK, scope in javascript
W3C explains scope.

ECMAScript scope is the set of variables, objects, and functions you have access toGlobal variables have global scope and local variables have local scope.  All global variables belong to the window object. In the codepen example below the script starts with the following: var name = "Greg"; . That name variable is defined globally in the global scope. When you create a function with variables inside it, the variables are locally scoped. items in a local scope are not visible in the global scope unless they are exposed.  In ECMAScript scopes are created with functions. What is closure? Well global variables can be made local with closures. If you have a function inside a function the inner function has access to the scope of the outer function. That is called Lexical Scope and is a example of closure. In the Lexical Scope any variables, objects or functions defined in the parent scope are available down the scope chain. Inside of a scope down the scope chain you can return things so that they are available in a parent scope. Also when you use jquery and you write jQuery '#elementID' you are accessing jQuery in global scope or namespace.

See the Pen JS Scope by Eric Thomas (@ericjasonthomas) on CodePen.

Maybe a better way to start explaining scope is to start with context and I will make that another post.