Reputation: 6772
I know an if
statement doesnt have its own scope like a function, meaning it shares the same scope with the containing context. If so, why am I allowed to redeclare the same variable again?
var foo = 123;
if (true) {
console.log(foo) // 123
var foo = 456; // Shouldnt it throw an error if refers to same variable?
}
console.log(foo) // 456
Upvotes: 3
Views: 934
Reputation: 41
We need to understand how the compiler and the Javascript runtime engine process and executes the code.
lets see how the compiler sees the below code snippet and creates appropriate scopes.
1. var foo = 123;
2. if (true) {
3. console.log(foo) // 123
4. var foo = 456;
5. }
6. console.log(foo) // 456
foo
identifier in global scope as it encounters that identifier for the first time.foo
identifier and it checks whether the identifier already exist in the global scope or not ( Note: var
does not has the block scope. So it looks one level up in the scope, which is global scope). Here global scope already had the identifier so, it goes to next line of code.It assigns and executes the code by using the scope created by the compiler.
foo
in the scope, as it exist it assigns the value 123
foo
in the block scope. As foo
does not exist in the block scope it looks one level above which is global scope. foo
is available in the global scope with a value of 123
. so console.log(foo)
is 123
foo
in the block scope. As foo
does not exist in the block scope it looks one level above which is global scope. foo
is available in the global scope so it re-assigns the value 456
to foo
. now foo is 456
.foo
identifier in the current scope which is global scope. foo
is available in the global scope with a value of 456
.Now, let see the question
var foo = 456;
is looks like redeclaring but actually it's not doing that. it uses the same globally declared identifier.
In some cases it's good to doing this kind of pattern for readability
purpose.
function test() {
var siteId;
if(condition) {
// more code 100+ lines
siteId = getId();
} else {
var siteId = 1001; // redeclaring here we are communicating the reader for sure we have the `siteId`
}
// other code
}
Upvotes: 3