Skip to content

Instantly share code, notes, and snippets.

@calvintychan
Created December 2, 2016 15:47
Show Gist options
  • Save calvintychan/48a5953ad48956aed95a6e82e60f24cd to your computer and use it in GitHub Desktop.
Save calvintychan/48a5953ad48956aed95a6e82e60f24cd to your computer and use it in GitHub Desktop.
Functions and their scope: declarations vs. expressions
/*
Resources:
- https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
- http://www.2ality.com/2011/04/ecmascript-5-spec-lexicalenvironment.html
*/
// function declarations uses the VariableEnvironment as scope
function f() {
return 12;
}
// function expressions use the LexicalEnvironment
// annoymous
var f = function () {
return 12;
};
// named
var f = function foo () {
return 12;
};
// self invoking
(function f() {
return 12;
})();
// Examples
function foo() {
var bar = function () {
return 3;
};
return bar();
var bar = function () {
return 8;
};
}
console.log(foo()); // 8
function boo() {
function bar() {
return 3;
}
return bar();
function bar() {
return 8;
}
}
console.log(boo()); // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment