DEV Community 👩‍💻👨‍💻

Ming-Shiuan Tsai
Ming-Shiuan Tsai

Posted on

JavaScript: Introduction to Scope (function scope, block scope)

What is Scope?

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 consider the global scope and the variables defined inside the global scope can be accessed and altered in any other scopes.

//global scope
var fruit = 'apple'
console.log(fruit);        //apple

function getFruit(){
    console.log(fruit);    //fruit is accessible here
}

getFruit();                //apple

Enter fullscreen mode Exit fullscreen mode

Local Scope

Variables declared inside the functions become Local to the function and are considered in the corresponding local scope. Every Functions has its own scope. Same variable 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
    }
}

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

//global scope


Enter fullscreen mode Exit fullscreen mode

Local scope can be divided into function scope and block scope. The concept of block scope is introduced in ECMA script 6 (ES6) together with the new ways to declare variables -- const and let.

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 variable for a function-scope accessibility.

function foo(){
    var fruit ='apple';
    console.log('inside function: ',fruit);
}

foo();                    //inside function: apple
console.log(fruit);       //error: fruit is not defined 


Enter fullscreen mode Exit fullscreen mode

Block Scope

A 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 fruit1 = 'apple';        //exist in function scope
        const fruit2 = 'banana';     //exist in block scope
        let fruit3 = 'strawberry';   //exist in block scope

    }
    console.log(fruit1);
    console.log(fruit2);
    console.log(fruit3);
}

foo();
//result:
//apple
//error: fruit2 is not defined
//error: fruit3 is not defined

Enter fullscreen mode Exit fullscreen mode

Lexical Scope

Another point to mention is the lexical scope. Lexical scope means the children scope have the access to the variables defined in the parent scope. The children functions are lexically bound to the execution context of their parents.

function foo1(){
    var fruit1 = 'apple';        
    const fruit2 = 'banana';     
    let fruit3 = 'strawberry';
    function foo2(){
        console.log(fruit1);
        console.log(fruit2);
        console.log(fruit3);
    }
    foo2();
}

foo1();

//result:
//apple
//banana
//strawberry

Enter fullscreen mode Exit fullscreen mode

For detailed comparison between var, let and const, take a look of JavaScript: var, let, const!

Top comments (31)

Collapse
 
nvs16 profile image
N V S ABHISHEK

Nice article.

Collapse
 
profgreatwonder profile image
Prof Great Wonder

Great article. Really helped me with understanding the block scope

Collapse
 
nguyentuan1696 profile image
Tuan Nguyen

Great clear explain !!!

Collapse
 
timrodz profile image
Juan Alejandro Morais

Great article - thanks for sharing! :)

Collapse
 
mdsameershaikh profile image
mdsameershaikh

Hi if you not have written {curly brackets} for explaining block scope, I could not understand it.

thanyou verymych for expaining in such easy language.

Collapse
 
caffro profile image
caffro

Thanks a mill, extremely helpful!

Collapse
 
tmsravan profile image
TMsravan

Nice explanation

Collapse
 
sashankramaraju profile image
Sashank Ramaraju

Very nice article on scopes !!!

Collapse
 
siddh profile image
Siddh

If we are not able to reassign the value in the variable that is defined with the const
then why it is changing his value every time, when the loop gets executed

const array = [1,2,3,4] ;

for (let index = 0; index < array.length; index++) {
const element = array[index];
console.log(element);
}

answer is

1
2
3
4

Collapse
 
devhamzaa profile image
Dev Hamza

you are storing the array[index] in element
you are not re-declaring but you are updating the value of element

Collapse
 
hafedbenchellali profile image
Hafed Benchellali

Thank you I Finally understood !

Collapse
 
b77748 profile image
B77748

Thank you, it's very clear now.

Collapse
 
banzaman profile image
mark rubanza

nice explanation
salut

Collapse
 
vickcharles profile image
Vikler Charles

Very helpful article! :)

Collapse
 
sanjarcode profile image
Muhammad Sanjar Afaq • Edited on

This is really helpful, embed this picture as a summary if you want.

Collapse
 
devhamzaa profile image
Dev Hamza

thanks dude i used it in my notes

Collapse
 
tuvudu profile image
Tuyen Vd.

thank for your explantation

Collapse
 
anhaltjan profile image
Jan Anhalt

This was very helpful, thank you very much! :)

Collapse
 
jfeijo profile image
João Antônio Feijó

Very cool explanation, straight to the point. I'm currently learning the scope subject on my bootcamp and you've made me understand it a lot better!

Collapse
 
saroj8455 profile image
Saroj Padhan

Nice explain of the scope

Collapse
 
saroj8455 profile image
Saroj Padhan

very nice explanation

Collapse
 
mylifewithmyexperiment profile image
SHASHI JAISWAL

very very clear and vivid explanation. awesome

Collapse
 
gidoskales profile image
GidoSkales

Well Orchestrated ....

Collapse
 
mhamadsiro profile image
Mohamad-serhan

Fantastic, great job

Collapse
 
johnkibirige005 profile image
Kibirige John

Thank you so much for the elaborative write-up

Collapse
 
bokooutman profile image
outman boko

Thank you so much for that explanation

Collapse
 
seven07del profile image
Prince Djangmah

Awesome, simplified and tactical. Loved it.

Collapse
 
mahmoudabdulmuty profile image
Mahmoud Abdulmuty

Good Explanation .. thanks alot

Collapse
 
umeredava profile image
Umar Sanil

Good

Collapse
 
kyuhyunhan profile image
KH

clear, helpful description of scope! Thanks!

Collapse
 
yusufnviiri profile image
yusufnviiri

Thank you for such Great work

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.