Variable Scope
JavaScript has two scopes: –
- Global
- Local
Global Scope
A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout your program. In a web browser, global variables are deleted when you close the browser window (or tab) but remain available to new pages loaded into the same window.
Local Scope
A variable that is declared inside a function definition is local. It is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function. Inside a function, if a variable has not been declared with var it is created as a global variable.
Local Scope
If there is a function inside a function the inner function can access outer function‟s variables but the outer function can not access inner function‟s variables. Function arguments (parameters) work as local variables inside functions.
Block Scope
Variables declared with var do not have block scope.
Block Scope
Identifiers declared with let and const do have block scope.
Variable Hoisting
Hoisting is JavaScript’s default behavior of moving declaration to the top of the function, if defined in a function, or the top of the global context, if outside a function.
Variable Hoisting
A variable can be used before it has been declared. Only variable declarations are hoisted to the top, not variable initialization.
Closure
A closure is a function having access to the parent scope. It preserves the data from the outside.
A closure is an inner function that has access to the outer (enclosing) function‟s variables.
For every closure we have three scopes:-
- Local Scope ( Own scope)
- Outer Functions Scope
- Global Scope