Skip to main content

Command Palette

Search for a command to run...

20. MEDIUM | Looping through Arrays in JavaScript

This article will talk about all the methods using which we can loop through arrays in javascript.

Updated
•7 min read•View as Markdown
S
Full-Stack Developer with 4 years' experience, specializing in backend development. Skilled in JavaScript, React, Python, Databases, and AWS. Known for building scalable web apps, leading teams, and maintaining strong client communication. Upskilling in Generative AI.

1. forEach()

Executes a provided callback function once for each element in an array.

Syntax

// Syntax using function declaration
array.forEach(function(currentElement, currentIndex, array) {
    // code to execute
});

// Syntax using arrow function
array.forEach((currentElement, currentIndex, array) => {
    // code to execute
});

Parameters:

  • currentElement (required) → current element being processed.

  • currentIndex (optional) → index of the current element.

  • array (optional) → the original array.

Key Characteristics

  • No Return Value: The forEach() method always returns undefined. It's not designed for transformations (use map() for that) or filtering (use filter()).
const result = [1,2,3].forEach(x => x*2);

console.log(result); // undefined
  • Cannot break or continue: You cannot use break to stop the iteration or continue to skip an iteration in a forEach() loop. A return statement inside the callback will only exit the current iteration, not the entire loop.

Usage

It's ideal for tasks like updating the DOM, logging data, or performing any operation that doesn't need to return a new array.

💡
Although, forEach() is not designed for array transformation, we can modify array elements.
let numbers = [1, 2, 3];

numbers.forEach((num, index, arr) => {
    arr[index] = num * 2;
});

console.log(numbers); // Output: [2, 4, 6]

2. map()

Creates a new array by applying a provided callback function to every element of the original array.

Syntax

// Syntax using function declaration
array.map(function(currentElement, currentIndex, array) {
    // code to execute
    return newValue;
});

// Syntax using arrow function
array.map((currentElement, currentIndex, array) => {
    // code to execute
    return newValue;
});

Parameters:

  • currentElement (required) → current element being processed.

  • currentIndex (optional) → index of the current element.

  • array (optional) → the original array.

Key Characteristics

  • Always returns a new array with the same length as the original.

  • Does not mutate the original array.

  • Requires a Return Value: The value returned by the callback function for each iteration becomes the corresponding element in the new array. If nothing is returned, the new array will contain undefined for that element.

const result = [1,2,3].map(x => {
    x * 2;
});
console.log(result); // Output: [undefined, undefined, undefined]


const result = [1,2,3].map(x => x * 2);
console.log(result); // Output: [2, 4, 6]
  • Skips Empty Elements: It does not execute the callback function for empty slots in sparse arrays.

3. filter()

Creates a new array containing only the elements from the original array that pass a specific condition implemented by a provided callback function.

Syntax

array.filter(function(currentElement, currentIndex, array) {
    // code to execute
    return true/false;
});

// using arrow function
array.filter((currentElement, currentIndex, array) => {
    // code to execute
    return true/false;
});

Parameters:

  • currentElement (required) → current element being processed.

  • currentIndex (optional) → index of the current element.

  • array (optional) → the original array.

The callback function must return true or false.

  • true → element is included in the new array.

  • false → element is excluded in the new array.

Key Characteristics

  • Always returns a new array with the same or smaller length as the original.

  • Does not mutate the original array.


4. reduce()

Executes a user-supplied "reducer" callback function on each element of an array, resulting in a single output value.

Syntax

array.reduce(callbackFn, initialValue);
  • callbackFn: A function executed on each element in the array, taking up to four arguments:

    1. accumulator (acc): The value returned from the previous call to the callback function. On the first call, if an initialValue is provided, it will be this value; otherwise, it will be the first element of the array.

    2. currentValue (curr): The current element being processed in the array.

    3. currentIndex (optional): The index of the current element.

    4. array (optional): The original array reduce() was called upon.

  • initialValue (optional): A value to use as the first argument to the first call of the callbackFn. If not supplied, the first element in the array is used as the initial accumulator value, and iteration starts from the second element.

Examples

// Example 1: Summing an array of numbers
const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15

// ================================================================

// Example 2: Counting occurrences in an array
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];

const count = fruits.reduce((tally, fruit) => {
  tally[fruit] = (tally[fruit] || 0) + 1;
  return tally;
}, {}); // Initial value is an empty object {}

console.log(count); // Output: { apple: 3, banana: 2, orange: 1 }

// ================================================================

// Example 3: Flatten array
const arr = [[1,2], [3,4], [5,6]];

const flat = arr.reduce((acc, curr) => {
    return acc.concat(curr);
}, []);

console.log(flat); // Output: [1,2,3,4,5,6]

// ================================================================

// Example 4:
const users = [
  {name: "Amit", age: 25},
  {name: "Rahul", age: 30},
  {name: "Priya", age: 25}
];

const groupByAge = users.reduce((acc, user) => {
    if(!acc[user.age]) {
        acc[user.age] = [];
    }
    acc[user.age].push(user);
    return acc;
}, {});

console.log(groupByAge);
/**
Output:
{
  25: [
    {name:"Amit", age:25},
    {name:"Priya", age:25}
  ],
  30: [
    {name:"Rahul", age:30}
  ]
}
*/

Usage

Commonly used for things like sum, grouping, counting, flattening arrays, etc.


Feature forEach() map() filter() reduce()
Purpose Perform side effects Transform elements Select elements Combine elements
Return undefined New array New array Single value
Output length Same as input array Same as OR smaller than input array

5. some()

Checks whether at least one element in an array passes a condition implemented by a provided callback function.

It returns:

  • true → if any one element passes the condition OR

  • false → if no elements pass the condition

It stops iterating as soon as it finds the first match (short-circuiting).

Syntax

array.some(function(currentElement, currentIndex, array) {
    // code to execute
    return condition;
});

// using arrow function
array.some((currentElement, currentIndex, array) => {
    // code to execute
    return condition;
});

Parameters:

  • currentElement (required) → current element being processed.

  • currentIndex (optional) → index of the element.

  • array (optional) → original array.

Example

// Example 1:
const users = [
  {name: "Amit", age: 20},
  {name: "Rahul", age: 17},
  {name: "Priya", age: 16}
];

const hasAdult = users.some(user => user.age >= 18);

console.log(hasAdult); // true

// ================================================================

// Example 2:
const numbers = [1, 3, 5, 7];

const result = numbers.some(num => num % 2 === 0);

console.log(result); // false

6. every()

Checks whether all elements in an array satisfy a specific condition provided by a callback function.

It returns:

  • true → if all elements pass the condition OR

  • false → if any element fails the condition

It stops execution early as soon as it finds the first element that fails the condition.


Happy reading!