Variable Scopes in JS
There are 2 types of variable scopes in JS:
- Global Scope
- Local Scope or Function Scope
Global Scope
By default, when we are coding in JavaScript, we are in root scope. Root scope is also called as Global scope, which is nothing but 'window' object. If we declare and initialize a variable outside of a function, it is created in Global scope.
var a = 10;
It can be accessed directly by its name, or using 'window' object.
console.log(a); // 10
console.log(window.a) // 10
console.log(window.a === a) // true
Function Scope
If we create a function and declare - initialize a variable inside it, then the variable is created in function scope. It cannot be accessed from outside the function. Function scope can access variables in root scope. But, root scope cannot access variables in function scope.
function foo() {
var a = 10;
console.log(a);
}
foo(); // This statement executes the function and prints 10.
console.log(a); // ReferenceError: c is not defined.
Scope in case of Name Conflict
This happens when a variable in function scope has exact same name as a variable in global scope. In this case, which value of the variable the program will see depends on where the program is seeing it from:
- If the program is seeing it from within the function, then it will see the function scoped value of that variable.
- If the program is seeing it from outside the function, then it will see the global scoped value of that variable.
- Global scoped variable can be accessed from within the function using 'window.variable'
var a = 10;
function foo() {
var a = 20; // Name conflict
console.log(a);
console.log(window.a);
}
foo(); // This statement executes the function. This prints 20 (function scope) and 10 (global scope)
console.log(a); // 10
Scope in case of undeclared variable in Function Scope
If a variable is not declared in function scope and directly initialized, then that variable will be created in Global Scope.
When a variable is directly declared in function scope, then:
- JS will first look in current scope i.e. function scope if a variable has been created with current scope.
- If yes, then JS will update the value of local variable.
- If not, then JS will look in global scope if a variable with same name has been created there already.
- If yes, then JS will update the value of global variable.
- If the variable is not found in global scope as well, then JS will create a variable in global scope and assign the value to it. This is also called as polluting the root scope.
- However, we can keep the scope clean by using strict mode in JS.