Skip to content

Instantly share code, notes, and snippets.

@richardTowers
Created January 24, 2013 20:06
Show Gist options
  • Save richardTowers/4627146 to your computer and use it in GitHub Desktop.
Save richardTowers/4627146 to your computer and use it in GitHub Desktop.
Eplanation of `var` in loops in javascript.
// 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