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:

var myArray = ['blue','green','orange','red'];

var counter = myArray.length;

while (counter--) {
    console.log(myArray[counter]);
}

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

    • 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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s