I was studying the concept of variable scope in JS, found this example on it:
(function() {
var foo = 1;
function bar() {
var foo = 2;
}
bar();
console.log(foo) //outputs 1
if(true) {
var foo = 3;
}
console.log(foo) //outputs 3
})();
output of this function is
1
3
Now I am confused how come foo
gets gets value 3 in second log. even when foo
is declared by using var
in if
statement. shouldn't the foo
declared in if
will have a new instance as it gets in bar()
??
A function in JavaScript defines a scope for variables declared using var , let and const . Any variable declared within that function is only accessible from that function and any nested functions. A code block ( if , for , etc.) defines a scope only for variables declared with the let and const keywords.
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not.
JavaScript has 3 types of scope: Block scope. Function scope. Global scope.
JavaScript has global scope and local scope. Variables declared and initialized outside any function become global variables. Variables declared and initialized inside function becomes local variables to that function. Variables declared without var keyword inside any function becomes global variables automatically.
if
does not introduce a scope block (I understand it does in some langauges). In JavaScript, only function() {}
creates a scope block.
There are only two kinds of scope in Javascript; function scope and global scope.
The code inside the if
statement doesn't have a scope of its own, so the variable inside the if
statement is the same one as the one outside it.
Declaring a variable more than once in a scope doesn't create more than one variable. The var
keyword inside the if
statement is ignored as the variable already is declared once in the scope, so it's just an assignment.
Note also that the declaration of variables is hoisted to the top of the scope, so even if a declaration is inside a code block that is not executed, the variable is still created:
var foo = 1; // a global variable
(function() {
console.log(foo) //outputs "undefined"
foo = 2; // sets the local variable
if(false) {
var foo = 3; // creates the local variable, but the assignment never happens
}
console.log(foo) //outputs 2
})();
console.log(foo) //outputs 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With