1

The following javascript works in Chrome and IE but errors out in Firefox because bar is undefined when assigned to callBar.

So who got their scope rules right?

function foo() {

    var callBar = bar;

    if (1 === 1) {
       callBar();
       function bar() {
          alert('yo');
       }
    }
}

foo();
1
  • Though it's an interesting brain teaser, do you really have some code like this? Functions (should) get hoisted and therefore defining them conditionally doesn't make sense. Commented Nov 17, 2011 at 16:42

1 Answer 1

5

Not sure who got it "right" according to the ECMA spec, but it doesn't really matter since you can't do this in all browsers and have to change your code :)

The simple explanation is that functions in if statement's aren't technically allowed and browsers do weird things with them. Some browsers treat this as an expression, others as a declaration. FF apparently treats it as an expression meaning it doesn't exist until the code gets to that point. A detailed write-up is available at http://kangax.github.com/nfe/

Sign up to request clarification or add additional context in comments.

Comments

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.