Sunday, June 09, 2013

JavaScript: Myths and realities of for..in

Nifty Snippets: Myths and realities of for..in:
"Probably the second most enduring myth about JavaScript is that the for..in statement loops through the indexes of an array. It doesn't, and if you write code that assumes it does, then even if the code doesn't break in its nice cozy nest on your computer, it's likely to as soon as you expose it to the complexities of the outside world."

Is simple c-style look may still the best?

for (index = 0; index < stuff.length; index++) {
     log.write(stuff[index]);
}

It may be, when used correctly. And that is not always:

stuff = [];
stuff[0] = "zero";
stuff[9999] = "nine thousand nine hundred and ninety-nine";
display(stuff.length); // shows 10000 (!)

Correct usage of "in" :

for (index in stuff) {
  if (stuff.hasOwnProperty(index) && String(Number(index)) === index) {
    log.write(stuff[index]);
  }
}

So this is a price of using "assembly language of the web"...

No comments: