Skip to content

Instantly share code, notes, and snippets.

@savelee
Last active July 25, 2016 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save savelee/70ee2846fcd4954737e11460cac531b7 to your computer and use it in GitHub Desktop.
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.
//Note the differences with both foo() functions
(function() {
console.log(typeof foo); // prints "function"
foo(); // logs "hello sencha"
function foo() {
console.log("hello sencha!");
}
})();
//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
})();
//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