Skip to content

Instantly share code, notes, and snippets.

@walesmd
Created September 21, 2014 00:31
Show Gist options
  • Select an option

  • Save walesmd/581f0e7f4c7a0304d4e3 to your computer and use it in GitHub Desktop.

Select an option

Save walesmd/581f0e7f4c7a0304d4e3 to your computer and use it in GitHub Desktop.
The differences between JavaScript function declarations and function expressions (and why variable hoisting is the reason for these differences).
// JavaScript code is run in two passes, the first pass
// does all the function declarations and determines the
// variables. The second pass actually executes your code.
// Example 1: Function Declaration
// Function declarations will always work because
// declarations are determined on the first pass and when
// you actually call the function is performed on the
// second pass.
foo();
function foo() {
console.log('Foo ran!');
}
// This works because the function declaration is always
// handled on the first pass. The interpreter runs this
// code as if you would have done:
function foo() {
console.log('Foo ran!');
}
foo();
}
// Example 2: Function Expression
// Function expressions will not always work, because the
// variable holding that function may be undefined. To truly
// understand this, we must first understand variable hoisting.
// Because JavaScript runs in two passes, all variable
// assignments are essentially "lifted" to the top of the
// current scope. For example:
console.log('This is a message.');
var msg = 'Blah blah blah';
// When JavaScript actually runs this code, the first pass
// discovers the variables then the code is run. So it's actually
// interpreted like this:
var msg;
console.log('This is a message.');
msg = 'Blah blah blah';
// And ths is why function expressions will not always execute
// whereas function declaration always will. Because when you write
// this code:
foo();
var foo = function() {
console.log('Running foo');
};
// It's actually being interpreted like this:
var foo;
foo(); // At this point, foo is "undefined"
foo = function() {
console.log('Running foo');
};
@yuranos

yuranos commented Jun 30, 2016

Copy link
Copy Markdown

Good one! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment