I wonder why the output is '1'.
var a
{
a = 1
function a() {}
a = 3
}
console.log(a) // 1
I wonder why the output is '1'.
var a
{
a = 1
function a() {}
a = 3
}
console.log(a) // 1
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 |
|---|---|---|
statement1It will declare a variable a in global scope
| variable | scope | value |
|---|---|---|
| a | global | undefined |
statement2It will assign 1 to the global variable a
| variable | scope | value |
|---|---|---|
| a | global | 1 |
statement3It declares a function named a in the block scope
| variable | scope | value |
|---|---|---|
| a | global | 1 |
| a | block | function |
statement4It 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 |
statement5It will log the nearest a, in this case the block scoped a's value is 3.
After the block completes, it will pop the
afrom the variables table and now the table will look like this:
| variable | scope | value |
|---|---|---|
| a | global | 1 |
statement6It will log the nearest a, and in this case, it is the global var, and the value is still 1