Scope in JavaScript

Abhay Jain
2 min readDec 19, 2020

Scope determines the visibility or accessibility of a variable or other resource in the area of your code.

Global Scope

There’s only one Global scope in the JavaScript document. The area outside all the functions is considered the global scope and the variables defined inside the global scope can be accessed and altered in any other scopes.

//global scope
var name = 'abhayjain13'
console.log(name); //abhayjain13
function print(){
console.log(name); //abhayjain13 is accessible here
}
print(); //abhayjain13

Local Scope

Variables declared inside the functions become Local to the function and are considered in the corresponding local scope. Every function has its own scope. The same variables can be used in different functions because they are bound to the respective functions and are not mutual visible.

//global scope
function foo1(){
//local scope 1
function foo2(){
//local scope 2
}

function foo3(){
//local scope 3
}
}
//global scope
function foo4(){
//local scope 4
}
//global scope

The local scope can be divided into function scope and block scope.

The concept of block scope is introduced in ECMAScript 6 (ES6) together with the new ways to declare variables — const and let.

1. Function Scope

Whenever you declare a variable in a function, the variable is visible only within the function. You can’t access it outside the function. var is the keyword to define a variable for function-scope accessibility.

function foo(){
var name ='abhayjain13';
console.log('inside function: ',name);
}
foo(); //inside function: abhayjain13
console.log(name); //error: name is not defined

2. Block Scope

Block scope is the area within if, switch conditions or for and while loops. Generally speaking, whenever you see {curly brackets}, it is a block. In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.

function foo(){
if(true){
var name1 = 'abhayjain'; //exist in function scope
const name2 = 'abhayjain1'; //exist in block scope
let name3 = 'abhayjain13'; //exist in block scope
}
console.log(name1);
console.log(name2);
console.log(name3);
}
foo();
//result:
//abhayjain
//error: name2 is not defined
//error: name3 is not defined

3. Lexical Scope

Lexical scope means the children’s scope have the access to the variables defined in the parent scope. The children’s functions are lexically bound to the execution context of their parents.

function foo1(){
var name1 = 'abhayjain';
const name2 = 'abhayjain1';
let name3 = 'abhayjain13';
function foo2(){
console.log(name1);
console.log(name2);
console.log(name3);
}
foo2();
}
foo1();//result:
//abhayjain
//abhayjain1
//abhayjain13

--

--

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.