Skip to main content

Posts

Showing posts from November, 2011

Lesson Learned: JavaScript For-In loops

For-In loops in JavaScript are really  nice... until they aren't. Not knowing exactly  how they work might bite you.  I'll start with an example: var arr1 = ["a", "b", "c", "d"]; for(var i in arr1)     console.log(i, arr1[i], i+1, arr1[i+1]); Seems simple enough.  What will be printed? 0 a 01 undefined 1 b 11 undefined 2 c 21 undefined 3 d 31 undefined  Whoops... I am an idiot!  That's not exactly what I wanted.  Note that i is a string , not a number .  I wasted an hour of my life trying to figure out why i+1 was not working properly... only to come to this horribly obvious conclusion.  It was totally worth a blog post... and a beer. Sometimes the old-fashioned for loops are better for Arrays: var arr1 = ["a", "b", "c", "d"]; for(var i = 0; i < arr1.length; i++)     console.log(i, arr1[i], i+1, arr1[i+1]);