user1539343
user1539343

Reputation: 1669

Scope of locally defined function in javaScript

I have this code snippet:

sayHi()

if (1) {
  function sayHi() {  alert(1)  }
} else {
  function sayHi() {  alert(2)  } // <--
}

How is it really working? The functions are defined in the if / else blocks. So how are they scoped outside the if / else blocks?

Upvotes: 0

Views: 28

Answers (2)

Barmar
Barmar

Reputation: 780974

The scope of the function is the entire containing function, because function declarations are hoisted. But the function doesn't get its definition assigned to it until the if or else block is executed. It's equivalent to:

var sayHi;
sayHi();

if (1) {
    sayHi = function() { alert(1); };
} else {
    sayHi = function() { alert(2); };
}

Upvotes: 1

Jim Cote
Jim Cote

Reputation: 1756

Everything is scoped at the function level in Javascript, not the block level as with most other languages. So if you define a var in a for loop, it is "hoisted" to the top of the containing function.

Upvotes: 0

Related Questions