Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielstreit/d4c465af957caf2d15ab to your computer and use it in GitHub Desktop.
Save danielstreit/d4c465af957caf2d15ab to your computer and use it in GitHub Desktop.
Function Declaration vs Function Expression
// What the difference between:
function declaration() {}; // This is a function declaration
// and
var expression = function() {}; // This is a function expression
// The function declaration is hoisted, definition and all.
// In the expression, only the var declaration is hoisted.
// The assignment of the anonomous function to that variable
// doesn't occur until the line on which the assignment
// occurs.
(function() {
var func = function() {
console.log('\tI came from an expression');
}
function func() {
console.log('\tI came from a declaration');
}
console.log('What will this print?');
func();
})();
// Although the func declaration came after the func
// expression, it was hoisted with its definition. So, the
// func expression definition actually comes after the func
// declaration in execution.
// Therefore, function declarations can be invoked before they are
// defined in the document. They will be hoisted on execution.
(function() {
console.log('Will declaration be invoke?');
declaration ? declaration() : console.log('\tNot gonna happen');
function declaration() {
console.log('\tOh Yeah!');
}
})();
// What about expression?
(function() {
console.log('Will expression be invoked?');
expression ? expression() : console.log('\tNoper');
var expression = function() {
console.log('\tYepper');
}
})();
// What about the combination?
(function() {
console.log('Will combo be called here?');
combo ? combo() : console.log('\tApparently Not')
var combo = function combo(who) {
console.log('\tI done been called');
}
console.log('What about here?');
combo ? combo() : console.log('\tOh no, Uh Oh');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment