0

Take a example of this one:

var is_android = true;
if (is_android) {
    function foo() {
        alert('I am Android');
    }
} else {
    function foo() {
        alert('I am NOT Android');
    }
}
foo();

It will be interpreted as

function foo() {
    alert('I am Android');
}
function foo() {
    alert('I am NOT Android');
}
var is_android;

is_android = true;
if (is_android) {

} else {

}
foo();

It will alert "I am NOT Android"; Looks like the second foo definition overwrites the first one.

It treats function definitions as declarations, my question is , when will this happen or is this always the case? How to make javascript treat something as a function definition?

Thanks.

Xinrui Ma
  • 2,065
  • 5
  • 30
  • 52
  • What you're experiencing is colloquially referred to as "hoisting". Have a look here: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html – Waxen Sep 10 '14 at 19:29
  • In your first example, you don't have any valid function declarations. What happens to them depends on your JavaScript engine. Try to `"use strict"` and it will throw. – Bergi Sep 10 '14 at 19:32

1 Answers1

4

Function declarations are always hoisted to the top of the containing scope. You should use an assignment if you want it to be conditional:

var is_android = true;
var foo;
if (is_android) {
    foo = function() {
        alert('I am Android');
    }
} else {
    foo = function() {
        alert('I am NOT Android');
    }
}
foo();
Barmar
  • 741,623
  • 53
  • 500
  • 612