Scope in JS, determines the accessibility of variables and functions at various parts in one’s code.
In general terms, the scope will let us know at a given part of code, what are the variables and functions that we can or cannot access.
There are three types of scopes in JS:
Global Scope
Local or Function Scope
Block Scope
Scope Chain:
JavaScript engine also uses Scope to find variables.
Let’s understand that using an example:
Ex:
var y = 24;
function favFunction(){
var x = 667;
var anotherFavFunction = function(){
console.log(x); // Does not find x inside anotherFavFunction, so looks for variable inside favFunction, outputs 667
}
var yetAnotherFavFunction = function(){
console.log(y); // Does not find y inside yetAnotherFavFunction, so looks for variable inside favFunction and does not find it, so looks for variable in global scope, finds it and outputs 24
}
anotherFavFunction();
yetAnotherFavFunction();
}
favFunction();