How To Iterate An Array In Javascript – Simple Examples

Welcome to a beginner’s tutorial on how to iterate an array in Javascript. So you have just begun with Javascript and trying to loop through a “dreaded” array?

The common ways to iterate an array in Javascript are:

  1. for (let INDEX in ARRAY) { ... }
  2. for (let ELEMENT of ARRAY) { ... }
  3. ARRAY.forEach(function (ELEMENT, INDEX) { ... });
  4. for (let i=0; i<ARRAY.length; i++) { ARRAY[i]; }
  5. let i = 0; while(i<ARRAY.length) { ARRAY[i]; i++; }

Yes, it’s that simple. But there are still a couple more methods, and reason on for more examples!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Array Iteration Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

ARRAY ITERATION

All right, let us now dive into the various ways to iterate/loop through an array in Javascript.

 

1) FOR … IN

1-for-in.js
var fruits = ["Apple", "Banana", "Orange", "Pear", "Durian"];
z
  console.log(i);  // 0, 1, 2, 3, 4
  console.log(fruits[i]); // Apple, Banana, ...
}

As in the above introduction, the for (INDEX in ARRAY) loop is probably one of the easiest of fuss-free ways to run through an array. But please take note, this loops through the indices, not the elements themselves.

 

2) FOR … OF

2-for-of.js
var fruits = ["Apple", "Banana", "Orange", "Pear", "Durian"];
for (let f of fruits) {
  console.log(f); // Apple, Banana, ...
}

As in the above introduction again, the for (ELEMENT of ARRAY) loop is the other fuss-free way to go through an array. But yes, this picks out the elements and not the indices.

 

 

3) FOREACH

3-foreach.js
var fruits = ["Apple", "Banana", "Orange", "Pear", "Durian"];
var eachFN = function(ele, idx, arr){
// ele: current element
// idx: current index
// arr: array itself
  console.log(ele); // Apple, Banana, Orance, ...
  console.log(idx); // 0, 1, 2, 3, 4
  console.log(arr); // The fruits array itself
};
fruits.forEach(eachFN);

The ARRAY.forEach() is an “alternative for loop”. As you can see, this takes in a callback function with 3 parameters instead – The element, index, and reference back to the array itself. Kind of useful if you want to “access both the index and element easily at the same time”.

 

4) FOR

4-for.js
var fruits = ["Apple", "Banana", "Orange", "Pear", "Durian"];
 
// ITERATE EVERY ELEMENT
console.log('== ALL ==');
for (let i=0; i<fruits.length; i++) {
  console.log(i); // 0, 1, 2, 3, 4
  console.log(fruits[i]); // Apple, Banana, Orange, ...
}
 
// ODD ELEMENTS
console.log('== ODD ELEMENTS ==');
for (let i=0; i<fruits.length; i+=2) {
  console.log(i); // 0, 2, 4
  console.log(fruits[i]); // Apple, Orange, Durian
}
 
// EVEN ELEMENTS
console.log('== EVEN ELEMENTS ==');
for (let i=1; i<fruits.length; i+=2) {
  console.log(i); // 1, 3
  console.log(fruits[i]); // Banana, Pear
}

Once upon a time, in the Stone Age of the Internet, for-in and for-of did not exist. This is how we iterate an array, using the good old “traditional” for loop. But please don’t be mistaken, this method is still very relevant these days – We can use this to loop through odd or even elements only… Even do funky Fibonacci if you want.

 

 

5) WHILE

5-while.js
var fruits = ["Apple", "Banana", "Orange", "Pear", "Durian"];
var i = 0;
while (i < fruits.length) {
  console.log(i); // 0, 1, 2, 3, 4
  console.log(fruits[i]); // Apple, Banana, Orange, ...
  i++;
}

This is another “traditional alternative” to iterate an array, using the while loop. A gentle reminder that do-while will run through at least once, if you need to do something to the array somehow.

 

6) EVERY & SOME

6-every-some.js
var thearray = [2, 4, 6, 11, 9];
var lessTen = function(ele, idx, arr){
// ele: current element
// idx: current index
// arr: array itself
  console.log(ele); // 2, 4, 6, 11, 9
  console.log(idx); // 0, 1, 2, 3, 4
  console.log(arr); // thearray itself
  return ele < 10;
};
console.log(thearray.every(lessTen)); // false
console.log(thearray.some(lessTen)); // true

Both ARRAY.every() and ARRAY.some() requires a callback function just like ARRAY.forEach(), but what they do is “quite different than usual”. As in, they run through the elements and do a check with provided callback function:

  • ARRAY.every() will return a true if all elements match the requirement in the callback function.
  • ARRAY.some() will return a true if at least one element matches the requirement in the callback function.

 

 

7) FILTER & REDUCE

7-filter-reduce.js
var thearray = [2, 4, 6, 11, 9];
 
// FILTER
var lessTen = function(ele, idx, arr){
// ele: current element
// idx: current index
// arr: array itself
  return ele < 10; // Keep if element less than 10
};
var filtered = thearray.filter(lessTen);
console.log(filtered); // 2, 4, 6, 6
 
// REDUCE
var plus = function(acc, cur, idx, arr){
// acc : Accumulated value
// cur: current element
// idx: current index
// arr : array itself 
  return acc + cur;
};
var total = thearray.reduce(plus);
console.log(total); // 2 + 4 + 6 + 11 + 9 = 32

Next, we have ARRAY.filter() and ARRAY.reduce(). They both run through the elements and work to “cut down” the array, but they process things differently:

  • ARRAY.filter() creates a new array containing elements that pass the check of the provided callback function.
  • ARRAY.reduce() uses the callback function to reduce the array down into a single variable instead.

 

8) MAP

8-map.js
var thearray = [2, 3, 8, 10];
var twice = function(cv, idx, arr){
// cv: current value
// idx: current index
// arr: array itself

  console.log(cv); // 2, 3, 8, 10
  console.log(idx); // 0, 1, 2, 3
  console.log(arr); // thearray
  return cv * 2;
};

var double = thearray.map(twice);
console.log(double); // 4, 6, 16, 20

This should be pretty straightforward too. ARRAY.map() also creates a new array, using the provided callback function to work on each element.

 

9) INDEXOF & LASTINDEXOF

9-index-of.js
var thearray = ["Foo", "Bar", "Hello", "Bar", "World"];
console.log(thearray.indexOf("Bar")); // 1
console.log(thearray.lastIndexOf("Bar")); // 3

// NOT FOUND WILL RETURN -1
console.log(thearray.indexOf("Barzzzz")); // -1

Yep. Every beginner should already know this one… ARRAY.indexOf() and ARRAY.lastIndexOf() searches for a given value in the array, and returns the index of it. The difference between the two is that ARRAY.indexOf() searches from first to last, while ARRAY.lastIndexOf() searches from last to first.

 

 

10) FIND & FINDINDEX

10-find.js
var thearray = [3, 2, 4, 5, 6];
var iseven = function(ele, idx, arr){
// ele: current element 
// idx: current index
// arr: the array itself

  return ele%2 == 0;
};

var firstodd = thearray.find(iseven);
console.log(firstodd); // 2

firstodd = thearray.findIndex(iseven);
console.log(firstodd); // 1

Finally, ARRAY.find() and ARRAY.findIndex() also does searching like ARRAY.indexOf() above. But we provide them with a custom “search function” instead. Both ARRAY.find() and ARRAY.findIndex() will return the first element that matches the given requirement –

  • ARRAY.find() returns the value of the element itself.
  • While ARRAY.findIndex() returns the index of the element.

 

USEFUL BITS & LINKS

That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEATSHEET

How To Iterate Array In Javascript (Click To Enlarge)

 

SUMMARY

Statement/Operator Description Reference Link
for (INDEX in ARRAY) { ... } Loops through an array and pick out the indices. Click Here
for (ELEMENT of ARRAY){ ... } Loops through an array and pick out the elements. Click Here
ARRAY.forEach(CALLBACK) Takes in a callback function with 3 parameters – Element, index, array. Click Here
ARRAY.length The number of elements in an array. Click Here
for (let i=0; i<ARRAY.length; i++) The “traditional” way to loop through an array.
while (i < ARRAY.length) { i++; } The other “traditional” way to loop through an array.
ARRAY.every(CALLBACK) Takes in a callback function to check if all elements of an array match a requirement. Click Here
ARRAY.some(CALLBACK) Takes in a callback function to check if at least one element of an array match a requirement. Click Here
ARRAY.filter(CALLBACK) Creates a new array, with elements that pass the check of the callback function. Click Here
ARRAY.reduce(CALLBACK) Uses the callback function to loop through the element, reduce it into a single variable. Click Here
ARRAY.map(CALLBACK) Creates a new array from an existing one. Map each element using the callback function. Click Here
ARRAY.indexOf(VALUE) Returns the index of the given value. Search from first-to-last. Click Here
ARRAY.lastIndexOf(VALUE) Returns the index of the given value. Search from last-to-first. Click Here
ARRAY.find(CALLBACK) Uses the callback function to search for an element in the array. Returns the first element that matches the requirement. Click Here
ARRAY.findIndex(CALLBACK) Uses the callback function to search for an element in the array. Returns the index of the element that matches the requirement. Click Here

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *