This post was most recently updated on July 31st, 2024
Hello everyone, in this post we will discuss about following points on JavaScript Scope
- What is scope?
- What is Global/Local Scope?
- What is lexical scope?
What is scope?
In JavaScript, scope determines the accessibility (visibility). Scope refers to the current context of your code. Scopes can be globally or locally defined for both functions and variables.
What is Global/Local Scope?
In JavaScript there are two types of scope:
- Local scope
- Global scope
Local scope: Variables declared within a JavaScript function, become local to the function. Local variables have local scope. They can only be accessed within the function.
1 2 3 4 5 |
// code here can not use bikeName function myFunction() { var bikeName= "Yamaha"; // code here can use bikeName } |
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is completed which means lifespan of local variables is only inside functions.
Global scope: A variable declared outside a function, becomes global. A global variable has global scope.
1 2 3 4 5 |
var bikeName= "Yamaha"; // code here can use bikeName function myFunction() { // code here can use bikeName } |
Since global variables are recognized inside all functions, global variables are created outside the function generally on top of the javascript file. Lifespan of global variables is within js file.
If you assign a value to a variable that has not been declared, it will automatically become a global variable.
1 2 3 4 5 6 |
myFunction(); // code here can use bikeName function myFunction() { bikeName= "Yamaha"; // code here can use bikeName } |
What is lexical scope?
Whenever you declare a function within another function, the inner function has access to the scope of the outer function, this is called Lexical Scope or Closure.
1 2 3 4 5 6 7 8 |
// Scope A var myFunction = function () { // Scope B var bikeName= 'Yamaha'; // defined in Scope B var myOtherFunction = function () { // Scope C: 'bikeName' is accessible here! }; }; |
Here variable bikeName declare inside scope B myFunction(), so scope is present inside myFunction() and myOtherFunction().