Created
January 24, 2013 20:06
-
-
Save richardTowers/4627146 to your computer and use it in GitHub Desktop.
Eplanation of `var` in loops in 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
// Normal variable: | |
var x = 7; | |
// Used like: | |
console.log(x); // => 7 | |
// Variable declared in a loop | |
for(var i = 0; i < 3; i++) { | |
// Used like: | |
console.log(i); // => 0,1,2 | |
} | |
// Loop with pre-declared variable: | |
var looper; | |
for(looper = 0; looper < 3; looper++) { | |
console.log(looper); // => 0,1,2 | |
} | |
// for ... in loops are the same: | |
var thing = { x: 1, y: 2, z: 3}; | |
for(var prop in thing) { // Be careful with this one! | |
console.log(prop); // x, y, z | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment