What array traversal methods are there in JavaScript? (for loop, for...in, for...of, forEach, map, filter, every, some)

February 1, 2023

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

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 and for...in?

Traversing an array in 8 different ways

for loop

  • You can use break to end the loop or use continue 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 with break, continue and return
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 the key in an array is the index
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 element

  • The 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 the map method

  • The declarative writing method is preferred by many developers, but you cannot use break and continue syntax to jump out of the loop in forEach, as shown in image figure below

    Uncaught SyntaxError: Illegal break statement
    Uncaught SyntaxError: Illegal break statement

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 a Boolean. If every element passes, it will return true, but if one of the element does not meet is false, it will end early and return false
  • The difference with some is that every method requires that every element in the array must pass the condition. But for some, 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 return true
  • The difference with every is that with the some method, as long as there is an element in the array that meets the condition in callback function, it will return true
[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 with break and continue syntax. Also using return will also be ignored in forEach

Bonus question: What is the difference between for...of and for...in?

  • for...of iterates the element value (value) in the array; and for...in iterates the key: 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 use for...in to iterate arrays, the main reasons are as follows:

    1. 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
      
    2. 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 use for...in method, you may operate on values that are not present in the array. But using for...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 ```

    3. Although the key:value iterated by for...in is index, for...in will use the String type as the key:value. So if we take index 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

    4. 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. And for...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 since Object does not have the property [Symbol.iterator], for...of cannot be used on Object.

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee