Javascript loop through array
This article will explain different ways to iterate over a javascript array with
1. for-in
loop,
2. for-of
loop,
3. forEach()
method,
4. values()
method, and
5. map() method with example programs.
Method 1: for-in loop
Javascript for-in loop can be used to loop through an array. Its syntax is
for(let variable in iterable) { }
where iterable is anything that can be iterated such as an array, object, string etc.
In every iteration, the variable will contain a property of an iterable. In case of an array, the variable will contain index of array elements.
To access the elements, use variable enclosed between square brackets after the array. Example,
let arr = [1,2,3,4]; for(let a in arr) { // access array element console.log(arr[a]); }
This prints
1
2
3
4
Remember that for-in
iterates over all enumerable properties(properties whose enumerable
flag is set to true
) of an array. In every iteration, the loop variable will contain a property of an array.
Since array indexes are considered its properties, the loop variable contains index in iteration.
This loop should be used with caution, as it may lead to indefinite result, such as in below example.
// add property to every array Array.prototype.abcd=123; let arr = [1,2,3,4]; for(let prop in arr){ console.log(prop, arr[prop]); }
Notice the first line adds a property abcd to every array in scope. Now, when you initialize a new array, it contains a property abcd with value 123.
Result of for-in
loop is now
0 1
1 2
2 3
3 4
abcd 123
Notice the new property added to array.
To ove rcome this situation, you need to check if a property belongs to the array using hasOwnProperty()
method as shown below
// add property to every array Array.prototype.abcd=123; let arr = [1,2,3,4]; for(let prop in arr) { if(arr.hasOwnProperty(prop)) { console.log(arr[prop]); } }
It is recommended to use for-of
or forEach()
or index based javascript for loop (discussed next) to loop through a javascript array.
Method 2: Using for-of loop
Javascript for-of
loop is also used to iterate over an array. Its syntax is
for(let variable of iterable) { }
Here, variable contains the array element in every iteration. So, you don’t need to access it explicitly using square brackets. Example,
let arr = [1,2,3,4]; for(let element of arr) { // access array element console.log(element); }
for-of
was introduced in Javascript ES6.
Method 3: Using forEach() method
Javascript forEach()
method accepts a function as argument and executes this function for every element of the array. The argument function is called callback function and it accepts following arguments :
1. element
The current array element for which the callback was invoked. This argument is mandatory.
2. index
Index of the current array element. This is optional.
3. array
The array on which forEach()
is being executed. This is optional.
Thus, forEach()
method can be easily used to loop through an array in javascript. Example,
let arr=[1,2,3,4]; arr.forEach(function(element) => { console.log(element); });
Callback function can also be written as an arrow function to make it more concise. Above code can also be written as
let arr=[1,2,3,4]; arr.forEach(element => { console.log(element); });
forEach()
was introduced in javascript ES5.
Do not use forEach() in below situations:
1. forEach()
cannot be terminated in between using break
statement. So, if such is the requirement, then do not use forEach()
.
2. Callback function of forEach()
should be synchronous. It does not wait for async function to complete or any promise to settle.
Method 4: Using for loop
Javascript for loop is the most primitive way of iterating over an array. Syntax of for loop is
for(let index=0; index < array.length; index++){ }
where index is a variable which ranges from 0 till the length of the array. So, for an array of length 5, above loop will execute with index value ranging from 0 to 4.
To access an array element, use index enclosed in square brackets after array. Example,
let arr=[1,2,3,4]; for(let index = 0; index < arr.length;index++){ console.log(arr[index]); }
Method 5: Using iterator
Javascript array values()
method returns an Array Iterator. This iterator has a next()
method which returns an object of below format
{value: v, done: boolean}
where value
holds the value of current array element and done
for all elements are false
.
When next()
is called after the last array element, value becomes undefined and done
becomes true
.
Below is the code example to loop through a javascript array using this method.
let arr = [1,2,3,4]; let iter = arr.values(); let element; // loop till done becomes true while(!(element = it.next()).done) { console.log(element.value); }
Method 6 : Using map() function
Similar to forEach()
, javascript Array.map() method is invoked over each element of the array. map()
also accepts a callback function as argument, which is called for every array element.
map()
returns a new array whose elements are the result of callback function applied over the elements of original array. Example,
let arr=[1,2,3,4]; let newArray = arr.map(function(element){ console.log(element); return element });
map()
is useful when you want to apply some operation over array elements and create a new array. For example, creating an array whose elements are square of another array, or an array whose elements are double the elements of some array.
Do NOT use map()
just for iterating over an array. Use forEach()
or for-of
to loop through a javascript array.
Loop through array of objects
Similar to an array of primitive values, we can loop through an array of javascript objects. Only difference is that in each iteration, the current array element will be an object.
Example program to iterate over an array of objects in javascript using for-of
loop is given below.
// define array of objects let arr=[ {id:1,name:'Google'}, {id:2,name:'Youtube'}, {id:3,name:'Facebook'} ]; for(let ele of arr){ console.log(ele.id,ele.name); }
This prints
1 “Google”
2 “Youtube”
3 “Facebook”
That is all on different ways to loop through a javascript array with examples.
Hope the article was useful.