Skip to content

Instantly share code, notes, and snippets.

@kerryChen95
Last active December 15, 2015 03:29
Show Gist options
  • Save kerryChen95/5194672 to your computer and use it in GitHub Desktop.
Save kerryChen95/5194672 to your computer and use it in GitHub Desktop.
Difference of two ways to "create" a function.
// example 1
(function () {
console.log(typeof func); // 'function'
function func () {}
console.log(typeof func); // 'function'
})();
// example 2
(function () {
console.log(typeof func); // 'undefined'
var func = function () {};
console.log(typeof func); // 'function'
})();
// For each variable declaration,
// a property with a same name but value `undefined`
// is added to the **variable object** of **execution context** (the former is a property of the latter),
// when entering a **execution context** (but before the code execution).
// example 3
(function () {
console.log(typeof func); // 'undefined'
(function func () {});
console.log(typeof func); // 'undefined'
})();
// Function object created by function-expression does not affect **variable object**,
// because it is not a declaration, will not be parsed on entering a **execution context**,
// but on code execution.
// In this example, **variable object** has no property named `func`.
// So, if such function object is not assigned to a variable or a property of an object,
// it will be only called on the spot or recursively,
// after that, you can not access it (even it has a name since function-expression does not affect **variable object**),
// and garbage collection will release its memory.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment