Skip to content

Instantly share code, notes, and snippets.

@FokkeZB
Last active December 21, 2015 04:19
Show Gist options
  • Save FokkeZB/6248899 to your computer and use it in GitHub Desktop.
Save FokkeZB/6248899 to your computer and use it in GitHub Desktop.
Declaring a function in a code block

In the wrong.js file below you'll get JSLint errors and after Alloy compiles both function declarations will be there. The right.js file shows how it should be done.

if (OS_ANDROID) {
var foo = function () {
alert('android');
}
} else {
var foo = function () {
alert('not android');
}
}
foo();
if (OS_ANDROID) {
function foo() {
alert('android');
}
} else {
function foo() {
alert('not android');
}
}
foo();
@skypanther
Copy link

This is because of a combination of hoisting and lack of block-level scope. Function declarations (the form you use in wrong.js) are hoisted entirely to the top of the scope, which would be outside your if(OS_ANDROID) block. That means the variable foo, and the function is contains are now moved outside the if block. And the second declaration overwrites the first.

Try it in your browser console:

if (true) {

  function foo() {
    alert('android');
  }

} else {

  function foo() {
    alert('not android');
  }
}

foo(); // alerts 'not android'

With the function statement (the form in your right.js example), the declaration of the variable foo is hoisted to the top of the scope, but its value assignment (putting the function inside that variable) is kept in its original place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment