1

Can someone explain why first function is running not the second one when I call it?

{
  function a() {
     console.log('first function')
  }
}

function a() {
     console.log('second function')
}

a()

If we declare them in a global scope they behave as expected, but inside block scope it's completely different. Why?

function a() {
     console.log('first function')
}

function a() {
     console.log('second function')
}

a()
norbekoff
  • 1,719
  • 1
  • 10
  • 21
  • FWIW, it gives "second function" in both cases for me… macOS Safari… – deceze Jul 04 '22 at 08:10
  • This behavior is not consistent (node runs the second function for your first example, and throws an error for the second). – pilchard Jul 04 '22 at 08:10
  • Functions aren't block scoped, so what exactly *is* the "expected behaviour"…? – deceze Jul 04 '22 at 08:12
  • @deceze es6 introduced block scoped functions see: [What are the precise semantics of block-level functions in ES6?](https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6) (also the reason the first example doesn't error in node as it doesn't see a conflict) – pilchard Jul 04 '22 at 08:22
  • @pilchard *When* in strict mode, which doesn't doesn't appear to be… – deceze Jul 04 '22 at 08:25
  • True, but that is different than your blanket statement. – pilchard Jul 04 '22 at 08:25

1 Answers1

1

The global function delaration move the function to top (hoisting), the one in the block stays at place.

The below result is from Edge 103.0.1264.37.

a(); // second

{
  function a() {
     console.log('first function')
  }
}

a(); // first

function a() {
     console.log('second function')
}

a(); // first
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392