7

The code below logs value a after assignments

var a = []
if (true) {
  a = 1
  function a() {}
  a = 2
  function a() {}
  a = 3
  console.log('0: ', a)
}
console.log('1: ', a)

I suspect the output might be:

0:  3
1:  3

But actually the code above logs

0:  3
1:  2

Why?

deceze
  • 510,633
  • 85
  • 743
  • 889
djy
  • 737
  • 6
  • 14

1 Answers1

0

How I understand it, there are two "a" variables.

One global, and one within the scope of the brackets.

On the first assignment, you are assigning it to the global.

When you declare the "a" function. It has local scope.

It assigns the current value in "a" to the global one.

Then when you assign a value to "a" again, it assigns it to the local scope variable.

For some reason, redeclaring the function name makes it assign local variable's value to the global variable. No idea why.

var a = [] // assigns to global

if (true) {
  a = 1 // assigns to global
  function a() {} // pushes value to global and creates a local "a" variable
  a = 2  // assigns to local
  function a() {} // pushes value to global
  a = 3  // assigns to local
  console.log('0: ', a) // outputs the local varaible
}
console.log('1: ', a)  // outputs the last pushed global which is 2
John
  • 5,942
  • 3
  • 42
  • 79
  • "*For some reason, redeclaring the function name makes it assign local variable's value to the global variable. No idea why.*" good old hoisting. Function declarations are always processed first `var foo= 1; function foo() {}` is processed as if `function foo() {}; var foo; foo = 1;` – VLAZ Dec 03 '20 at 07:51