What array traversal methods are there in JavaScript? (for loop, for...in, for...of, forEach, map, filter, every, some)
February 1, 2023
In basic JavaScript interview, the method of traversing the array is often asked. This article lists the most commonly used array traversal methods in JavaScript, including for
loops, native methods of arrays (forEach
, map
...), and common array traversal questions in interviews.
This article is divided into two parts:
- 8 ways to iterate over the array
- What is the difference between
for...of
andfor...in
?
Traversing an array in 8 different ways
for loop
- You can use
break
to end the loop or usecontinue
to jump out of the current loop - Imperative writing is more verbose
let arr = [0, 1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
if (i > 2) break;
console.log(arr[i]);
}
// 0
// 1
// 2
for...of
- This is a ES6 feature. It is more concise than the
for
loop - Like the
for
loop, it can be used withbreak
,continue
andreturn
const arr = ["apple", "orange", "banana"];
for (const item of arr) {
if (item === "orange") continue;
console.log(item);
}
// apple
// banana
for...in
- When using
for...in
,key:value
is being iterated, and thekey
in an array is theindex
const arr = ["apple", "orange", "banana"];
for (const item of arr) {
console.log(item);
}
// 0
// 1
// 2
Below are the native methods you can use to iterate an array
forEach
forEach
will execute the callback function for each elementThe
forEach
method will only iterate over the original array and will not return a new array. So if you need to construct a new array from an old array, you should use themap
methodThe declarative writing method is preferred by many developers, but you cannot use
break
andcontinue
syntax to jump out of the loop inforEach
, as shown in image figure below
map
map
executes the provided callback function for each element and returns an new array
const arr = [1, 2, 3, 4];
const newArr = arr.map((x) => x + 1);
console.log(newArr);
// [2,3,4,5]
console.log(arr);
// [1,2,3,4] // original array is not changed
filter
filter
returns a new array, and filter out elements that do not pass the condition in the provided callback function
const arr = [19, 2, 13, 40];
const newArr = arr.filter((x) => x > 18);
console.log(newArr);
// [19, 40]
console.log(arr);
// [19, 2, 13, 40] // original array is not changed
every
every
will check whether each element in the array passes the condition in the provided callback function, and finally returns aBoolean
. If every element passes, it will returntrue
, but if one of the element does not meet isfalse
, it will end early and returnfalse
- The difference with
some
is thatevery
method requires that every element in the array must pass the condition. But forsome
, only one element needs to pass the condition.
[12, 5, 8, 130, 44].every((x) => x > 10); // false
[12, 54, 18, 130, 44].every((x) => x > 10); // true
some
- The method is similar to
every
, it will test whether each element of the array passes the condition of the provided callback function, if one of the element meets the condition, it will end early and returntrue
- The difference with
every
is that with thesome
method, as long as there is an element in the array that meets the condition in callback function, it will returntrue
[2, 5, 8, 1, 4].some((x) => x > 10); // false
[12, 5, 8, 1, 4].some((x) => x > 10); // true
Bonus question: Which methods will change the original array?
The array methods mentioned above will not directly change the original array by default, unless the function we pass in does some processing on the original array.
Bonus question: Which methods will return a new array?
map
and filter
will return a new array, so if you are writing immutable code in React, you often need to use these two methods.
Bonus question: What is the difference between for
loop and forEach
?
- There is a difference in wording,
forEach
is more concise forEach
cannot end the entire iteration early, nor can it be used withbreak
andcontinue
syntax. Also usingreturn
will also be ignored inforEach
Bonus question: What is the difference between for...of
and for...in
?
for...of
iterates theelement value (value)
in the array; andfor...in
iterates thekey: value
.var arr = [10, 20, 30]; for (let value of arr) { console.log(value); } //10 20 30 var arr = [10, 20, 30]; for (let value in arr) { console.log(value); } //0 1 2
In most cases,
for...in
will be used to iterate objects, but it is not recommended to usefor...in
to iterate arrays, the main reasons are as follows:When there is an empty item in the array, using the
for...in
method ignores the item.let a = ["a", , "c"]; for (let x in a) { console.log(x); } // 0 2 for (let x of a) { console.log(x); } // a undefined c
for... in
will check whether the properties of the object are enumerable. If true, it will iterate out all the names of these properties. Since some JavaScript libraries may create methods on the Array prototype, if you usefor...in
method, you may operate on values that are not present in the array. But usingfor...of
can avoid this issue.```jsx Array.prototype.foo = 1;
let a = [1, 2, 3]; for (let x in a) { console.log(x); }
// 0 1 2 foo ```
Although the key:value iterated by
for...in
isindex
,for...in
will use the String type as the key:value. So if we takeindex
to do calculations may cause unexpected results.jsx let a = [1, 2, 3]; for (let x in a) { console.log(x + 1); } // 01 11 21
The iteration of
for...in
does not guarantee that the order is correct. This situation is very difficult to use on an array, because when we want to iterate the values in the array, we usually want the order to be correct. Andfor...of
will first check the[Symbol.iterator]
property of the object, and then use[Symbol.iterator].next()
to iterate out the values one by one to ensure that the order is correct. But sinceObject
does not have the property[Symbol.iterator]
,for...of
cannot be used on Object.