Skip to content

Instantly share code, notes, and snippets.

@mattscilipoti
Last active October 14, 2015 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattscilipoti/3bdcdbe7b011b94f348a to your computer and use it in GitHub Desktop.
Save mattscilipoti/3bdcdbe7b011b94f348a to your computer and use it in GitHub Desktop.
JS: Compare for/each and for/in
// console.log("test");
var names = ["matt", "adam"];
// 1: use for/in, w/var
console.log("Starting 1 (for/in)...")
var idx = -9;
console.log("idx: before1", idx)
for (var idx in names) {
console.log("idx: in1", idx);
}
console.log("idx: after1", idx)
console.log("******************")
// 1a: use for/in, w/o var
console.log("Starting 1a (w/o for/in)...")
var idx = -8;
console.log("idx: before1a", idx)
for (idx in names) {
console.log("idx: in1a", idx);
}
console.log("idx: after1a", idx)
console.log("******************")
// 2: try it, initializing to 0
console.log("Starting 2 (for/loop w/init)...")
var idx = -7;
console.log("idx: before2", idx)
for (var idx=0; idx < names.length; idx++) {
console.log("idx: in2", idx);
}
console.log("idx: after2", idx)
console.log("******************")
// 3: try it without initializing to 0
console.log("Starting 3 (for/loop w/o init)...")
var idx = -6;
console.log("idx: before3", idx)
for (var idx; idx < names.length; idx++) {
console.log("idx: in3", idx);
}
console.log("idx: after3", idx)
@mattscilipoti
Copy link
Author

Interested? Just copy and paste into your js console.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment