Agility6
Agility6

Reputation: 63

The output result is 1, what is the reason for this

I wonder why the output is '1'.

var a
{
  a = 1
  function a() {}
  a = 3
}
console.log(a) // 1

Upvotes: 6

Views: 182

Answers (1)

vighnesh153
vighnesh153

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
Execute statement1

It will declare a variable a in global scope

variable scope value
a global undefined
Execute statement2

It will assign 1 to the global variable a

variable scope value
a global 1
Execute statement3

It declares a function named a in the block scope

variable scope value
a global 1
a block function
Execute 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
Execute 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
Execute statement6

It will log the nearest a, and in this case, it is the global var, and the value is still 1

Upvotes: 12

Related Questions