Loop elegantly through a JavaScript Array

I’ve been reading JavaScript Enlightenment to try and understand the language. There is beauty, and power, hiding behind the covers of JavaScript, but I haven’t clicked yet. I still don’t really get prototypal inheritance and what ‘this’ really means. There is power in understanding closure and scope, too, I am sure. This small book is recommended to see where the beauty is.

20943392

I’d like to share one bit of code which I found elegant: looping through an array:

[code language=”javascript”]
var myArray = [‘blue’,’green’,’orange’,’red’];

var counter = myArray.length;

while (counter–) {
console.log(myArray[counter]);
}
[/code]

It relies on the fact that integer values that are not 0 or -0 are ‘truthy’.

2 thoughts on “Loop elegantly through a JavaScript Array”

  1. Errr – wait. Falsy values are 0, -0, null, ” (empty string), null, undefined, and NaN. So all integer values apart from 0 are truthy. So, ooops, yes, you’re right. Corrected!

Leave a Comment