Skip to content

Instantly share code, notes, and snippets.

@walesmd
Created November 7, 2014 23:00
Show Gist options
  • Save walesmd/10239cb58f9c47608dbc to your computer and use it in GitHub Desktop.
Save walesmd/10239cb58f9c47608dbc to your computer and use it in GitHub Desktop.
Fun Friday Challenge: Why do these two code examples work differently?
/* This example results in
* undefined is not a function
*/
doLog();
var doLog = function() {
console.log('Log!');
}
/* This example results in
* Log!
*/
doLog();
function doLog() {
console.log('Log!');
}
@btaspikhov
Copy link

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.

@peterchon
Copy link

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.

@btaspikhov
Copy link

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