Code highlights logo
Pricing

4 Easy Ways to Iterate Over Arrays in JavaScript

November 13, 2023
4 Easy Ways to Iterate Over Arrays in JavaScript
Table of Contents
  • for Loop
  • forEach() Method
  • for...of Loop
  • map() Method
  • Performance Considerations

In JavaScript, arrays are a type of object used for storing multiple values in a single variable. Each value in the array is an element. You can iterate, or loop, over an array in JavaScript in several ways. This tutorial will explore some of the most common methods.

for Loop

A for loop is a control flow statement, which allows code to be executed repeatedly. To iterate over an array with a for loop, you can use the array's length property.

1var arr = [1, 2, 3, 4, 5];
2for (var i = 0; i < arr.length; i++) {
3console.log(arr[i]);
4}

This will log each number on its own line, from 1 to 5.

forEach() Method

The forEach() method executes a provided function once for each array element. This is a more modern, functional programming style and is featured prominently in our JavaScript course.

1var arr = ['apple', 'banana', 'cherry'];
2arr.forEach(function(element) {
3console.log(element);
4});

This will log each string on its own line, from apple to cherry.

for...of Loop

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects and more. It combines the best parts of the for and forEach().

1var arr = [10, 20, 30, 40];
2for (var element of arr) {
3console.log(element);
4}

This will log each number on its own line, from 10 to 40.

map() Method

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

1var arr = [1, 2, 3, 4, 5];
2var newArr = arr.map(function(element) {
3return element * 2;
4});
5console.log(newArr);

This will log the new array [2, 4, 6, 8, 10].

Performance Considerations

The for loop is the fastest way to iterate over an array in JavaScript, followed by forEach(), for...of, and finally map(). However, the differences are often negligible, and readability or convenience might often dictate your choice.

Stay Ahead with Code highlights

Join our community of forward-thinkers and innovators. Subscribe to get the latest updates on courses, exclusive insights, and tips from industry experts directly to your inbox.

3D Letter

Start learning for free

If you've made it this far, you must be at least a little curious. Sign up and grow your programming skills with Code Highlights.

Start learning for free like this happy man with Code Highlights