Home | SkillForge Blog | How to Loop Through an Array in JavaScript

How to Loop Through an Array in JavaScript

JavaScript, Uncategorized, Web Design

Video version of this post:

How to Loop Through a JavaScript Array

In JavaScript, there’s a helpful way to access every item that’s in an Array and it’s called a for in loop.  It has the functionality, by default to go through and only run however many times there are items in the array.  To take a look at this we can set up an array like so:

var ninjaTurtles = [“Leo”, “Ralph”, “Don”, “Mikey”];

Now we could use a for loop and go through it like so:

for(i=0;i<ninjaTurtles.length;i++){
document.write(ninjaTurtles[i]+”<br>”);
}

This works and it would print out all their names to the page, but this way requires that we use the length property, that we set up a beginning and end value and then have to use i++ to make sure it counts correctly.  There’s just a lot to it.  Well, there’s a simpler, more concise way of doing it and that is using the for in loop.  Here is what it would look like:

for(i in ninjaTurtles){
document.write(ninjaTurtles[i]+”<br>”);
}

As you can see, the loop is a lot simpler and easier to read.  Instead of having three parts you only have one simple statement.  This loop inherently knows how many times to run.  It will run one time for each item that is contained in the array.  You don’t have to specifically tell it a number of times to loop.  Because of that, there is also no need to tell it when to end, where to start, or what to do each time the loop completes.  It’s just easier to read and write.

The variable i works the same way as it did in the previous example, it will contain the index value or position of each item in the array.  The first time it runs, i will be equal to 0.  The next time i will be 1 and so on.  For in loops are great and it makes coding loops a little more simple which I’m sure we all appreciate.  If you want to learn more be sure to check out our JavaScript Training.  Have an amazing day!