Do you know the scope of the (var) keyword differs in the Function and Block scopeβπ π
But How it differsβLet's know it.π
Table of contents
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