Local and global scope

36 Views Asked by At

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

There are 1 best solutions below

3
Quentin On

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)