Scope in JavaScript

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

Global Scope

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

Local Scope

//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

1. Function Scope

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

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

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

--

--

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

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