Created
April 30, 2014 14:43
-
-
Save nealfennimore/11429033 to your computer and use it in GitHub Desktop.
Creating Scope Javascript
This file contains 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
// How do we create scope? | |
function drive() { | |
var innerState = 66; | |
console.log(innerState); // Should print 66 | |
} | |
drive(); //66 | |
console.log(innerState); // Should print undefined or raise not defined | |
// Will print 66 when var is removed from innerState | |
// ------------------ | |
// Functions create scope in JS. What happens when they're nested? | |
function processData(data) { | |
data.forEach(processItem); | |
function processItem(item) { | |
var reversed = item.split("").reverse().join(""); | |
console.log(reversed); | |
} | |
} | |
processData(["Apple", "Orange", "Pear"]); | |
// epplA, egnarO, reaP | |
processItem("Peach"); | |
// processItem not defined | |
// ----------------------------- | |
function processData(data) { | |
var joinChar = "-"; // Works here | |
data.forEach(processItem); | |
function processItem(item) { | |
// var joinChar = "-"; // Works here too | |
var reversed = item.split("").reverse().join(joinChar); | |
console.log(reversed); | |
} | |
} | |
processData(["Apple", "Orange", "Pear"]); | |
// e-p-p-l-A, e-g-n-a-r-O, r-e-a-P | |
processItem("Peach"); | |
// processItem still does not work | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment