Limiting access to your variables and hiding them from other parts of your application is an important part of designing software.
What would happen if you have two different variables in the same scope with the same name, also known as a naming collision in your app?
Understanding scope and using it to your advantage helps make your code easier to reason about and reduces bugs.
Global vs Local Scope
Variables defined outside of a function, are in the global scope and can be accessed anywhere in your program. Wrapping a variable in a function, it is now in local scope and cannot be accessed by anything outside of that function.
Here is an example of nested functions
const partition = (list, predicate) => {
const result = [[],[]];
const item = "Oh, hello there.";
result.forEach((item, index, list) => {
console.log(item); // ??
// TODO
});
};
partition([1, 2, 3, 4], n => n % 2);
// → [[1, 3], [2, 4]]
How many functions do you see in the example above?
Take a look at the slides to see a diagram of how each of these functions map to their own local scopes:
Load content from slides.com?
Loading external content may reveal information to 3rd parties. Learn more
Allow
Block Statements
const and let vs var
Execution Context
When a function is called, an execution context is created. The execution context is commonly conceptualized as an object with properties:
scopeChain: { ... }, // contains its own activationObject and other activationObject of the parent execution contexts
context: valueOfThis
}
You can imagine that the Activation Object is created inside the Execution Context Object once a function is called. It contains all the local variables, arguments.
We also have the scope chain inside of the execution context which contains references to the activation objects of outer, parent scopes.
Context refers to the value of the keyword this ! While execution context encapsulates context, they are different.
Lexical Scope
When we have functions nested inside other functions, functions retain access to the scope of the parent function. This is lexical scope. Where a function is defined, not called is what determines how a function is able to access variables in the parent scope.