Created
April 7, 2016 18:19
-
-
Save hellofromtonya/06cf54cc0387fbc0e45a719e5e9c4148 to your computer and use it in GitHub Desktop.
JavaScript Hoisting Example
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
(function ( document, $, undefined ) { | |
/***** | |
* SHOWING HOISTING WITH A VARIABLE | |
*/ | |
// Let me show hoisting to you by demonstrating a variable and it's | |
// initialization with a value | |
// 1. You get "undefined" here - but NOT an error. | |
console.log( hoistingVariable ); | |
var hoistingVariable = 'I am initializing it now.'; | |
// Now it outputs the actual assigned variable | |
console.log( hoistingVariable ); | |
/****** | |
* Now with functions | |
*/ | |
// Notice that you are calling this BEFORE the function has been declared | |
// It calls the function. It hoisted it's declaration and knows it's a | |
// function when you call it here. (notice the code where you declare it is below) | |
doThingA(); | |
/***** | |
* Ok this one behaves differently because you are assigning it to a variable. | |
*/ | |
// Notice that if you console.log out the variable, it says "undefined". The | |
// variable is hoisted, but not the function that is assigned to it. | |
console.log( doThingB ); | |
// But with this one you will get an error | |
doThingB(); | |
/******* | |
* Functions | |
*/ | |
function doThingA() { | |
// do things here | |
console.log( 'doThingA' ); | |
} | |
var doThingB; | |
doThingB = function() { | |
//do other things here | |
console.log( 'doThingB' ); | |
} | |
})( document, jQuery ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment