0

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?

2
  • 1
    They aren't. When I run it, I get TypeError: sayHi is not a function Commented Feb 12, 2017 at 5:56
  • This question seems very unclear......... Commented Feb 12, 2017 at 5:58

2 Answers 2

1

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); };
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

This is not completely true. var and function declarations are function scoped, but let, const and class declarations are block scoped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.