What array traversal methods are there in JavaScript? (for loop, for...in, for...of, forEach, map, filter, every, some)
Tags: javascript, webdev, beginners, programming
Published: 2023-01-23 11:50:44

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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/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

  ```jsx
  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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/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`

### [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)

- When using `for...in`, `key:value` is being iterated, and the `key` in an array is the `index`

---

**Below are the native methods you can use to iterate an array**

### [`forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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 Syntax](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nqve8cri033e5rpqnmr1.png)


### [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)

- `map` executes the provided callback function for each element and returns an new array

### [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)

- `filter` returns a new array, and filter out elements that do not pass the condition in the provided callback function

### [`every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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.

```jsx
[12, 5, 8, 130, 44].every((x) => x > 10); // false
[12, 54, 18, 130, 44].every((x) => x > 10); // true
```

### [`some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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`

```jsx
[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 interation 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`.

```jsx
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:**

a. When there is an empty item in the array, using the `for...in` method ignores the item.

```jsx
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
```

b. `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
```

c. 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
```

d. 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.

---


Thanks for reading.

If you like the content, check out the free frontend interview prep resources my friends and I curated at [explainthis.io](https://www.explainthis.io/).

I have got frontend engineer offers from both startup and FAANG companies. I would like to help as many people as possible to land a job. If you have any questions regarding to frontend engineering or frontend interview. Feel free to reach out to me at hello@explainthis.io