Last active
July 25, 2016 14:14
-
-
Save savelee/70ee2846fcd4954737e11460cac531b7 to your computer and use it in GitHub Desktop.
JavaScript Hoisting: Variable declarations using var are treated as if they are at the top of the function (or global scope, if declared outside of a function) regardless of where these were placed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Note the differences with both foo() functions | |
(function() { | |
console.log(typeof foo); // prints "function" | |
foo(); // logs "hello sencha" | |
function foo() { | |
console.log("hello sencha!"); | |
} | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Note the differences with both foo() functions | |
(function() { | |
console.log(typeof foo); // prints "undefined" | |
foo(); // Error: foo is not a function | |
var foo = function() { | |
console.log("hello sencha!"); | |
} | |
})(); | |
//this difference is because the browsers interprets is at the code below: | |
(function() { | |
var foo; | |
console.log(typeof foo); // prints "undefined" | |
function __anon() { | |
console.log("hello sencha!"); | |
} //some anonymous function | |
foo(); // Error: foo is not a function | |
foo = __anon; //and now we bind anonymous function to foo | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//ES2015 | |
//Notice what happends when variables are defined with the let identifier: | |
(function() { | |
console.log(typeof foo); // ReferenceError: can't access lexical declaration `foo' before initialization | |
foo(); // I won't even get here. | |
let foo = function() { | |
console.log("hello sencha!"); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment