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!'); | |
} |
The first example is a function expression, the second is a function statement. And since function statement is subject to hoisting, it is moved to the top of the scope regardless of it's placement.
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A javascript file is run in a 2-pass read. The first pass parses syntax and collects function definitions, and the second pass actually executes the code. This means that at execution time for example1.js the system knows about the function and runs it, while for the second one it doesn't as it didn't save that in memory during the first pass.