Array fix:
To create an array of strings, do not use for..in , use the vanilla for loop:
var tags = ["Favorite", "Starred", "High Rated"]; for (var i = 0; i < tags.length; i++) {
Output:
Favorite Starred High Rated
Proper use of for..in :
It is intended for the properties of an object, for example:
var tags2 = {"Favorite": "some", "Starred": "stuff", "High Rated": "here"}; for (var tag in tags2) { // enumerating objects properties console.log("My property: " + tag +" value is " +tags2[tag]); }
Output:
My property: Favorite value is some My property: Starred value is stuff My property: High Rated value is here
Side effects of for..in with arrays:
Don't take my word for it, let's see why not use it: for..in in arrays can have side effects. Take a look:
var tags3 = ["Favorite", "Starred", "High Rated"]; tags3.gotcha = 'GOTCHA!'; // not an item of the array // they can be set globally too, affecting all arrays without you noticing: Array.prototype.otherGotcha = "GLOBAL!"; for (var tag in tags3) { console.log("Side effect: "+ tags3[tag]); }
Output:
Side effect: Favorite Side effect: Starred Side effect: High Side effect: GOTCHA! Side effect: GLOBAL!
See the demo script for these codes.
source share