Reputation: 63
I wonder why the output is '1'.
var a
{
a = 1
function a() {}
a = 3
}
console.log(a) // 1
Upvotes: 6
Views: 182
Reputation: 5416
This is not something that you should do in your code. Will try to break down what is happening.
Pre-requisites
Adding some identifiers to the code
// statement1
var a
{
// statement2
a = 1
// statement3
function a() {}
// statement4
a = 3
// statement5
console.log(a)
}
// statement6
console.log(a)
Explanation
Initial variables table
variable | scope | value |
---|---|---|
statement1
It will declare a variable a
in global scope
variable | scope | value |
---|---|---|
a | global | undefined |
statement2
It will assign 1
to the global variable a
variable | scope | value |
---|---|---|
a | global | 1 |
statement3
It declares a function named a
in the block scope
variable | scope | value |
---|---|---|
a | global | 1 |
a | block | function |
statement4
It is assigning value 3
to a
and it will pick the nearest defined a
to assign the value to. In this case, it will assign 3
to the block scoped a
variable | scope | value |
---|---|---|
a | global | 1 |
a | block | 3 |
statement5
It will log the nearest a
, in this case the block scoped a
's value is 3
.
After the block completes, it will pop the
a
from the variables table and now the table will look like this:
variable | scope | value |
---|---|---|
a | global | 1 |
statement6
It will log the nearest a
, and in this case, it is the global var, and the value is still 1
Upvotes: 12