6

I wonder why the output is '1'.

var a
{
  a = 1
  function a() {}
  a = 3
}
console.log(a) // 1
Agility6
  • 63
  • 4
  • 1
    You should not declare functions in a code block, behavior of the code becomes unpredictable. If you remove the function declaration, you'll get `3` as you probably have expected. I'd recall I've seen a warning about this unpredictable behavior at [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block), but it's not there anymore. – Teemu Nov 04 '22 at 15:46
  • 3
    While obviously this would be a terrible structure to use in real code, it does make for an interesting question. – DBS Nov 04 '22 at 15:47
  • 2
    Actually the warning is there: ["_In non-strict code, function declarations inside blocks behave strangely. Do not use them._"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block#block_scoping_rules_with_var_or_function_declaration_in_non-strict_mode), just not with red background. – Teemu Nov 04 '22 at 15:54
  • 1
    Does this answer your question? [How does this hoisting work with block scope?](https://stackoverflow.com/questions/66756997/how-does-this-hoisting-work-with-block-scope) – 0stone0 Nov 04 '22 at 16:18
  • 1
    Does this answer your question? [Function declaration in block moving temporary value outside of block?](https://stackoverflow.com/questions/58619924/function-declaration-in-block-moving-temporary-value-outside-of-block) – 0stone0 Nov 04 '22 at 16:29

1 Answers1

12

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

vighnesh153
  • 4,354
  • 2
  • 13
  • 27