What is a variable scope?
The visibility and accessibility of a variable is determined by its scope. JavaScript has three scopes:
- Global scope
- Local scope and
- Block scope
Global Scope
A variable that can be accessible everywhere in the script.
Local Scope
If you declare a variable inside a function are local to the function. They are called local variables.
Output:
I am from say
I am from global
Scope Chain
If interpreter cannot find a variable in its local context, then it looks for it in parent contexts until it's found. This is called scope chain.
Output:
Hello I am message
In the above script, the JavaScript performs the following:
- It looks up for the variable message in the current context (Functional Execution Context) of the say(). But it cannot find it.
- So it goes out of the function and looks in the outer execution context which is the global execution context. It found the message variable there.
- The way that JavaScript resolves a variable is by looking at in its current scope, if it cannot find the variable then it goes to the outer scope. This process is a Scope Chain.
Block Scope
ES6 provides the let and const keywords that allow you to declare variables in a block scope.
Generally whenever you see curly braces { }, it is a block. It can be the area within the if else, switch conditions or for , do while and while loops.
let is block scoped, var is function scoped.
Comments
Post a Comment