0

var a = 1

function b() {
  a = 20
  return

  function a() {}
}
b()
console.log(a)

I thought the output would be 20 but its 1 ? The execution context of function b would access variable a from the GEC and update its value imo. Why is it so?

1 Answers1

1

function declarations declare a variable sharing the name of the function in the current scope (like var does) and are hoisted.

function a therefore creates a local variable a inside function b and is that that variable that you overwrite.


Some people prefer to use arrow functions with explicit variable declarations. That creates an error instead of having the behaviour that surprised you.

var a = 1

function b() {
  a = 20
  return

  const a = () => {}
}
b()
console.log(a)
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335