Created
December 2, 2016 15:47
-
-
Save calvintychan/48a5953ad48956aed95a6e82e60f24cd to your computer and use it in GitHub Desktop.
Functions and their scope: declarations vs. expressions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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