Skip to content

Instantly share code, notes, and snippets.

@lizlongnc
Last active August 29, 2015 14:07
Show Gist options
  • Save lizlongnc/15fea0befc3895794a37 to your computer and use it in GitHub Desktop.
Save lizlongnc/15fea0befc3895794a37 to your computer and use it in GitHub Desktop.
JS for(in) - use with JS objects
for(in) loops through the enumerable properties of an object, not the indexes of an array
console.log('The primary use case for for(in) is to enumerate the properties of an object and will result in unexpected results if used with an Array');
console.log('for(in) gives you the index positions of the items if used in the array and not an objecct:');
console.log('the results below are from using a for(in) with var myNewArray = ["a", "b", "c", "d"]');
var myNewArray = ["a", "b", "c", "d"];
for (var i in myNewArray) {
console.log('i', i);
};
// prints 0 1 2 3
// Which is generally unexpected. The primary use case for for(in) is to enumerate the properties of an object:
console.log('\nbut if used on the object: var o = { x: 10, y: 20 }; you get:');
var o = { x: 10, y: 20 };
for (var i in o) {
console.log('property(s) of object o:', i);
};
// prints x y
console.log('\nin general, it\'s recommended that you use Object.keys to get the set of keys for an object, and then use the normal array enumeration:');
console.log('Object.keys(o).forEach...');
var o = { x: 10, y: 20 };
Object.keys(o).forEach(function (keyName) {
console.log('property(s) of object o:', keyName);
});
// prints x y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment