Programming
Radzivon Alkhovik
Low-code automation enthusiast
July 4, 2024
A low-code platform blending no-code simplicity with full-code power 🚀
Get started free
July 4, 2024
8
min read

JavaScript Array Iteration

Radzivon Alkhovik
Low-code automation enthusiast
Table of contents

Array iteration is a fundamental concept in JavaScript that allows developers to loop through and manipulate elements within an array. JavaScript provides a variety of methods to iterate over arrays, from traditional loops (while, do...while, for, for...in, for...of) to modern array methods (forEach, map, filter, reduce, reduceRight). Each method is suited to different tasks, such as filtering, transforming, or reducing data. Advanced methods like flatMap, Array.from, keys, entries, and the spread operator offer additional flexibility and functionality. Mastering these techniques enables developers to write concise, efficient, and expressive code for handling arrays, which is essential for building robust JavaScript applications. Understanding these methods also ensures compatibility with modern browsers, making them practical for contemporary web development.

Key Takeaways:  JavaScript offers various methods for array iteration, including traditional loops (while, do...while, for, for...in, for...of) and modern array methods (forEach, map, filter, reduce, reduceRight). Each method has unique features suitable for different use cases, from simple iterations to complex transformations. Mastering these techniques enables developers to write efficient, expressive code for manipulating arrays, essential for building powerful JavaScript applications. Most methods are supported in modern browsers, ensuring wide compatibility.

Write the code even if you are beginner with Latenode's AI Assistent

What are Loops in JavaScript?

Loops in JavaScript are control structures that allow developers to repeatedly execute a block of code until a specific condition is met. They provide a way to automate repetitive tasks and process arrays or collections of data efficiently. JavaScript offers several types of loops, including while, do...while, for, for...in, and for...of, each with its own syntax and use cases.

How to Loop Through an Array with a While Loop in JavaScript

The while loop through array of objects javascript executes a block of code as long as a specified condition evaluates to true. It is a versatile loop that can be used to iterate over arrays by manually managing the index variable. Here's an example of using a while loop to iterate over an array:


const numbers = [1, 2, 3, 4, 5];
let i = 0;

while (i < numbers.length) {
  console.log(numbers[i]);
  i++;
}

In this example, the while loop continues to execute as long as the index i is less than the length of the numbers array. The loop prints each element to the console and increments the index variable.

How to Loop Through an Array with a do...while Loop in JavaScript

The do...while loop is similar to the while loop, but it guarantees that the code block is executed at least once before checking the condition. Here's an example of using a do...while array loop in javascript:


const fruits = ['apple', 'banana', 'orange'];
let i = 0;

do {
  console.log(fruits[i]);
  i++;
} while (i < fruits.length);

In this case, the loop prints each fruit to the console and increments the index variable. The loop continues until the condition i < fruits.length evaluates to false.

How to Loop Through an Array with a for Loop in JavaScript

The for loop is a compact and commonly used loop structure in JavaScript. It combines the initialization, condition, and increment/decrement expressions in a single line. Here's an example of using a for loop to iterate over an array:



const colors = ['red', 'green', 'blue'];

for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}

The for loop initializes the index variable i to 0, checks the condition i < colors.length, and increments i after each iteration. The loop prints each color to the console.

How to Loop Through an Array with a for...in Loop in JavaScript

The for...in loop is used to iterate over the properties of an object. When used with arrays, it iterates over the array indices. Here's an example:



const persons = ['Alice', 'Bob', 'Charlie'];

for (let index in persons) {
  console.log(index + ': ' + persons[index]);
}

In this example, the for...in loop iterates over the indices of the persons array. It prints each index and its corresponding value to the console.

How to Loop Through an Array with a for...of Loop in JavaScript

The for...of loop, introduced in ECMAScript 2015 (ES6), provides a more concise and readable way to iterate over iterable objects, including arrays. It directly accesses the values of the array without the need for an index variable. Here's an example:

javascript



const numbers = [1, 2, 3, 4, 5];

for (let number of numbers) {
  console.log(number);
}

In this case, the for...of loop iterates over each element of the numbers array and assigns it to the variable number. The loop prints each number to the console.

How to Loop Through an Array with a forEach Loop in JavaScript

The forEach() method is a built-in array method that executes a provided function once for each array element. It offers a more expressive and functional approach to array iteration. Here's an example:



const fruits = ['apple', 'banana', 'orange'];

fruits.forEach((fruit) => {
  console.log(fruit);
});

In this example, the forEach() method is called on the fruits array. It takes an arrow function as an argument, which receives each fruit as a parameter and prints it to the console.

Other Array Iteration Methods

JavaScript provides several other array iteration methods that offer powerful capabilities for manipulating and transforming arrays. These methods include:

  • map(): Creates a new array by calling a provided function on every element in the array.
  • filter(): Creates a new array with all elements that pass the test implemented by the provided function.
  • reduce(): Executes a reducer function on each element of the array, resulting in a single output value.
  • every(): Tests whether all elements in the array pass the test implemented by the provided function.
  • some(): Tests whether at least one element in the array passes the test implemented by the provided function.

We will explore these methods in more detail in the following sections.

JavaScript Array forEach()

The forEach() method executes a provided function once for each array element. It does not return a new array but allows you to perform an action on each element. Here are a couple of examples:

Example 1



const numbers = [1, 2, 3, 4, 5];

numbers.forEach((number) => {
  console.log(number);
});

In this example, the forEach() method is used to print each number in the numbers array to the console.

Example 2



const fruits = ['apple', 'banana', 'orange'];
const upperCaseFruits = [];

fruits.forEach((fruit) => {
  upperCaseFruits.push(fruit.toUpperCase());
});

console.log(upperCaseFruits);

In this example, the forEach() method is used to convert each fruit in the fruits array to uppercase and push it into a new array upperCaseFruits.

JavaScript Array map()

The map() method creates a new array by calling a provided function on every element in the array. It returns a new array with the results of the function call for each element. Here are a couple of examples:

Example 1



const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((number) => {
  return number ** 2;
});

console.log(squaredNumbers);

In this example, the map() method is used to create a new array squaredNumbers by squaring each number in the numbers array.

Example 2



const persons = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const names = persons.map((person) => {
  return person.name;
});

console.log(names);

In this example, the map() method is used to extract the name property from each object in the persons array and create a new array names containing only the names.

JavaScript Array filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function. It returns a new array containing the elements that satisfy the condition. Here are a couple of examples:

Example 1



const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((number) => {
  return number % 2 === 0;
});

console.log(evenNumbers);

In this example, the filter() method is used to create a new array evenNumbers by filtering the numbers array to include only even numbers.

Example 2



const persons = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const adultPersons = persons.filter((person) => {
  return person.age >= 18;
});

console.log(adultPersons);

In this example, the filter() method is used to create a new array adultPersons by filtering the persons array to include only persons who are 18 years old or older.

JavaScript Array reduce()

The reduce() method executes a reducer function on each element of the array, resulting in a single output value. It takes an accumulator and the current element as arguments and returns the accumulator for the next iteration. Here are a few examples:

Example 1



const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(sum);

In this example, the reduce() method is used to calculate the sum of all numbers in the numbers array. The initial value of the accumulator is set to 0.

Example 2



const words = ['Hello', 'World', 'JavaScript'];
const sentence = words.reduce((accumulator, currentValue) => {
  return accumulator + ' ' + currentValue;
});

console.log(sentence);

In this example, the reduce() method is used to concatenate all words in the words array into a single sentence. The accumulator is initialized with an empty string.

Example 3



const persons = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const totalAge = persons.reduce((accumulator, person) => {
  return accumulator + person.age;
}, 0);

console.log(totalAge);

In this example, the reduce() method is used to calculate the total age of all persons in the persons array. The accumulator is initialized to 0.

JavaScript Array reduceRight()

The reduceRight() method is similar to the reduce() method, but it executes the reducer function from right to left (from the last element to the first element). Here are a couple of examples:

Example 1



const numbers = [1, 2, 3, 4, 5];
const reversedSum = numbers.reduceRight((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

console.log(reversedSum);

In this example, the reduceRight() method is used to calculate the sum of all numbers in the numbers array, starting from the last element and moving towards the first element.

Example 2



const words = ['Hello', 'World', 'JavaScript'];
const reversedSentence = words.reduceRight((accumulator, currentValue) => {
  return accumulator + ' ' + currentValue;
});

console.log(reversedSentence);

In this example, the reduceRight() method is used to concatenate all words in the words array into a single sentence, starting from the last word and moving towards the first word.

JavaScript Array every()

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns true if the function returns true for all elements, and false otherwise. Here are a couple of examples:

Example 1



const numbers = [2, 4, 6, 8, 10];
const allEven = numbers.every((number) => {
  return number % 2 === 0;
});

console.log(allEven);

In this example, the every() method is used to check if all numbers in the numbers array are even. It returns true since all numbers satisfy the condition.

Example 2



const persons = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const allAdults = persons.every((person) => {
  return person.age >= 18;
});

console.log(allAdults);

In this example, the every() method is used to check if all persons in the persons array are adults (age greater than or equal to 18). It returns true since all persons satisfy the condition.

JavaScript Array some()

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if the function returns true for at least one element, and false otherwise. Here's an example:

Example



const numbers = [1, 2, 3, 4, 5];
const hasEvenNumber = numbers.some((number) => {
  return number % 2 === 0;
});

console.log(hasEvenNumber);

In this example, the some() method is used to check if there is at least one even number in the numbers array. It returns true since the array contains even numbers.

Advanced Array Iteration Methods

JavaScript provides additional array iteration methods that offer more advanced functionality. These methods include:

  • flatMap(): Creates a new array by applying a function to each element and then flattening the result.
  • from(): Creates a new array from an array-like or iterable object.
  • keys(): Returns a new Array Iterator object that contains the keys for each index in the array.
  • entries(): Returns a new Array Iterator object that contains key-value pairs for each index in the array.
  • with(): Returns a new array with a specified element replaced with a new element. (Introduced in ES2023)

Let's explore these methods in more detail.

JavaScript Array flatMap()

The flatMap() method first maps each element of an array using a mapping function, then flattens the result into a new array. It combines the functionality of map() and flat() in a single method. Here's an example:

Example



const numbers = [1, 2, 3, 4, 5];
const mappedAndFlattened = numbers.flatMap((number) => {
  return [number, number * 2];
});

console.log(mappedAndFlattened);

In this example, the flatMap() method is used to map each number in the numbers array to an array containing the number and its double, and then flatten the resulting arrays into a single array.

Browser Support

The flatMap() method is supported in modern browsers, including Chrome 69+, Edge 79+, Firefox 62+, Safari 12+, and Opera 56+.

JavaScript Array from()

The Array.from() method creates a new array from an array-like or iterable object. It allows you to convert objects that have a length property and indexed elements into an array. Here's an example:

Example

array in javascript example:



const arrayLike = {
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3
};

const array = Array.from(arrayLike);
console.log(array);

In this example, the Array.from() method is used to convert an array-like object into an actual array.

Browser Support

The Array.from() method is supported in modern browsers, including Chrome 51+, Edge 15+, Firefox 54+, Safari 10+, and Opera 38+. It is not supported in Internet Explorer.

JavaScript Array keys()

The keys() method returns a new Array Iterator object that contains the keys for each index in the array. It allows you to iterate over the array indices. Here's an example:

Example



const fruits = ['apple', 'banana', 'orange'];
const iterator = fruits.keys();

for (const key of iterator) {
  console.log(key);
}

In this example, the keys() method is used to obtain an iterator that contains the keys (indices) of the fruits array. The for...of loop is then used to iterate over the keys and print them.

Browser Support

The keys() method is supported in modern browsers, including Chrome 51+, Edge 15+, Firefox 54+, Safari 10+, and Opera 38+. It is not supported in Internet Explorer.

JavaScript Array entries()

The entries() method returns a new Array Iterator object that contains key-value pairs for each index in the array. Each entry is an array in the form of [index, element]. Here's an example:

Example

array in javascript example:



const fruits = ['apple ', 'banana', 'orange']; const iterator = fruits.entries();
for (const [index, element] of iterator) { console.log(${index}: ${element}); }


In this example, the `entries()` method is used to obtain an iterator that contains key-value pairs for each index in the `fruits` array. The `for...of` loop is then used to destructure each entry into `index` and `element` variables and print them.

JavaScript Array with() Method

The `with()` method is a new addition introduced in ECMAScript 2023 (ES2023). It allows you to create a new array with a specified element replaced with a new element. It provides a way to update an element in an array without mutating the original array. Here's an example:

Example



const numbers = [1, 2, 3, 4, 5];
const updatedNumbers = numbers.with(2, 10);

console.log(numbers);
console.log(updatedNumbers);


In this example, the with() method is used to create a new array updatedNumbers where the element at index 2 is replaced with the value 10. The original numbers array remains unchanged.

JavaScript Array Spread (...)

The spread operator (...) allows you to expand an array into individual elements. It can be used to concatenate arrays, pass arrays as arguments to functions, or create new arrays with existing elements. Here's an example:

Example



const fruits = ['apple', 'banana'];
const moreFruits = ['orange', 'grape'];
const allFruits = [...fruits, ...moreFruits];

console.log(allFruits);

In this example, the spread operator is used to concatenate the fruits and moreFruits arrays into a new array allFruits.

Browser Support

The spread operator is supported in modern browsers, including Chrome 51+, Edge 15+, Firefox 54+, Safari 10+, and Opera 38+. It is not supported in Internet Explorer.

Wrapping Up

JavaScript provides a wide range of array iteration methods that allow developers to javascript loop through array javascript, manipulate elements, and create new arrays based on specific conditions. In this article, we explored various methods, including traditional loops like while, do...while, for, for...in, and for...of, as well as modern array methods like forEach(), map(), filter(), reduce(), every(), some(), and more.

Understanding and leveraging these array iteration techniques empowers developers to write concise, efficient, and expressive code when working with arrays for each in javascript. By mastering these methods, you can perform complex operations on arrays with ease and build powerful JavaScript array loop applications.

Write the code even if you are beginner with Latenode's AI Assistent

FAQ

What is the difference between for...of and for...in loops?

The for...of loop is used to iterate over the values of an iterable object, such as an array, while the for...in loop is used to iterate over the enumerable properties of an object, including array indices.

When should I use map() instead of forEach()?

Use map() when you want to create a new array by transforming each element of an existing array. Use forEach() when you want to perform an action on each element of an array without creating a new array.

How can I iterate over an array in reverse order?

You can use the reverse() method to reverse the order of elements in an array and then iterate over the reversed array using any of the iteration methods discussed in this article.

How can I exit a loop prematurely?

You can use the break statement to exit a loop array in javascript prematurely. When encountered inside a loop, break immediately terminates the loop and transfers control to the next statement after the loop.

Related Blogs

Use case

Backed by