Do you know the scope of the (var) keyword differs in the Function and Block scopeβ“πŸ˜Ž 😎

But How it differs❓Let's know it.😁

Β·

1 min read

Table of contents

No heading

No headings in the article.

Let's talk about the var keyword declared in the global scope βž–

function foo() {

console.log(a);

}

πŸ‘‰ var a = 2;

πŸ“ž foo();

πŸ‘‰ When Var is declared global then it is the same as it is inside the global window object. πŸ†’ right 😁

πŸ‘‰ So due to the global object and the outer lexical environment reference the above snippet of code will return 2 😎

Let's talk about the var keyword declared in the function scope βž–

function foo() {

πŸ‘‰ var a = 2;

console.log(a);

};

πŸ“ž foo();

πŸ‘‰ When the Var keyword is declared inside the function scope then the var's scope will not point global window object instead var will point to the function scope only. πŸ†’ right 😁

πŸ‘‰ So due to the var pointing to function scope in the above snippet of code that's why it will return 2.

Let's talk about the var keyword declared in the block scope βž–

if( 5 > 2 ){

πŸ‘‰ var a = 2;

};

console.log(a);

πŸ‘‰ When a var keyword is declared in the block scope then the var's scope will always point to the global window object. πŸ†’ right 😁

πŸ‘‰ So due to the var pointing to the global window object inside block scope in the above snippet of code that's why it will return 2.

EndFragment

Β