What is Scope?

Scope in JavaScript is the area where we have valid access to variables or functions. JavaScript has three types of Scopes. Global Scope, Function Scope, and Block Scope(ES6).

  • Global Scope - variables or functions declared in the global namespace are in the global scope and therefore is accessible everywhere in our code.
//global namespace
var g = 'global';
function globalFunc() {
function innerFunc() {
console.log(g); // can access "g" because "g" is a global variable
}
innerFunc();
}
  • Function Scope - variables,functions and parameters declared within a function are accessible inside that function but not outside of it.
function myFavoriteFunc(a) {
if (true) {
var b = 'Hello ' + a;
}
return b;
}
myFavoriteFunc('World');
console.log(a); // Throws a ReferenceError "a" is not defined
console.log(b); // does not continue here
  • Block Scope - variables (let,const) declared within a block can only be access within it.
function testBlock() {
if (true) {
let z = 5;
}
return z;
}
testBlock(); // Throws a ReferenceError "z" is not defined

Scope is also a set of rules for finding variables. If a variable does not exist in the current scope it look ups and searches for a variable in the outer scope and if does not exist again it looks up again until it reaches the global scope if the variable exists then we can use it if not it throws an error. It searches for the nearest variable and it stops searching or looking up once it finds it. This is called Scope Chain.

/* Scope Chain
Inside inner function perspective
inner's scope -> outer's scope -> global's scope
*/
//Global Scope
var variable1 = 'Comrades';
var variable2 = 'Sayonara';
function outer() {
//outer's scope
var variable1 = 'World';
function inner() {
//inner's scope
var variable2 = 'Hello';
console.log(variable2 + ' ' + variable1);
}
inner();
}
outer();
// logs Hello World
// because (variable2 = "Hello") and (variable1 = "World") are the nearest
// variables inside inner's scope.

Javascript Scopes


October 23, 2022
1291