Global scope applies to any variable that is declared outside of a function in the top-level scope. Variables that have a global scope can be accessed from anywhere in your code.
- “b” is accessible from within the functions local scope due to “b” being scoped globally.
- Also important to note, variables declared without (var, const or let) are scoped globally.
- “b” is not accessible outside of its local scope.
- “b” is available to the “nestedFunc” function through the scope chain or what's called “lexical scoping.” The nested function has access to all variables that are declared in its parent functions local scope and so on up the scope chain all the way to the global scope.
- In this example, we have two separate declarations of the variable “b”, while in the previous example we logged the value from the parent scope. The nested function will always check for a local instance of the variable we are referencing, if it does not find what it is looking for in its current scope it will move up the scope chain until it does or throws an error.
- “b” is locally scoped to the “nestedScope” function here. We cannot access it from the parent “scope” function, the scope chain does not work from the top down.
Thus far we have looked at local scope from a function scope standpoint. With ECMA script 6 (ES6) the concept of block scope was introduced together with the new variable declaration keywords const and let.
Block scope is defined within for/while loops and if/switch statements. Const and let are the only variable declaration keywords that support local scope as noted in the code below.
Whew, that was a lot of scope talk, I hope this helps you understand this concept a bit better. If I missed anything or you have anything to add leave a comment below. Happy Coding!
This article was migrated over from Medium. Original article can be found here