Created
November 7, 2014 23:00
-
-
Save walesmd/10239cb58f9c47608dbc to your computer and use it in GitHub Desktop.
Fun Friday Challenge: Why do these two code examples work differently?
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
/* This example results in | |
* undefined is not a function | |
*/ | |
doLog(); | |
var doLog = function() { | |
console.log('Log!'); | |
} |
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
/* This example results in | |
* Log! | |
*/ | |
doLog(); | |
function doLog() { | |
console.log('Log!'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just read an article on JavaScript Scoping and Hoisting. Peterchon is right:
In the first example only declaration of doLog variable will be hoisted and it will receive it's value only at execution time. That is why it's value is undefined as it didn't receive it's value when it is referred to. In the second example doLog function declaration and it's body will be hoisted and so executed in the appropriate order.