Created
September 10, 2017 03:31
-
-
Save StevenJL/52e481fa2ad21df9ef8a1ded45473bce to your computer and use it in GitHub Desktop.
javascript_scoping
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
/* | |
GLOBAL SCOPE | |
*/ | |
var global_var = "mango"; // global_var is accessible everywhwere | |
/* | |
Function scope is lexical | |
*/ | |
function otherFunction() { | |
var outer_var = "foo"; | |
// inner_var is not accessible here | |
function innerFunction() { | |
var inner_var = "bar"; | |
// outer_var is accessible here | |
} | |
} | |
/* | |
Using function scope to create a closure | |
*/ | |
function closure_maker() { | |
var closure_var = 'remember_me'; | |
return function() { | |
return closure_var; | |
} | |
} | |
closure = closure_maker(); | |
closure(); //=> 'remember_me'; | |
/* | |
Blocks have the same scope as their containing scope. | |
*/ | |
if (true) { | |
var block_var = 'wat'; | |
} | |
block_var // => 'wat' | |
for(var i=0; i < 10; i++){ | |
console.log("hello block scope"); | |
} | |
i //=> 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment