6 different ways to loop through an array in JavaScript (with examples)

6 different ways to loop through an array in JavaScript (with examples)

Handling an array of data is unavoidable and it’s very common when it comes to building any sort of application. In this article, I’m going to show you 6 different approaches to how you can loop through an array of data in Javascript together with...

Handling an array of data is unavoidable and it’s very common when it comes to building any sort of application. In this article, I’m going to show you 6 different approaches to how you can loop through an array of data in Javascript together with examples so that you can relate and later apply it in your development.

1. for Loop

The basic for loop has the following syntax:

for (initialization; condition; update statement) {
    // code block to be executed
}

The for loop statement basically uses three expressions:

  • Initialization — to initialize the loop variable with a starting value and it will only be executed once
  • Condition — defines when the loop will stop looping
  • Update Statement — is executed every time after the code block within the loop has been executed. Normally it’s being used to increment the loop variable

Note: break statement can be used to “jump out” of a for loop.

Example of using for loop:

var myArray = [
    {id: 1, name: 'John', age: 12},
    {id: 2, name: 'Jane', age: 14},
    {id: 3, name: 'Martin', age: 13},
    {id: 4, name: 'Katie', age: 17},
    {id: 5, name: 'Louis', age: 11}
];

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

/*
Output:
    John
    Jane
    Martin
    Katie
    Louis
*/

2. for/of Loop

The for/of loop has the following syntax:

for (variable of iterator) {
    // code block to be executed
}
  • Iterator —refers to the array to be iterated
  • Variable — The value of the next iteration (if any) will be assigned to the variable. Variable has to be declared with either const, let, or var to hold the value.

Note: break statement can be used to “jump out” of a for/of loop.

Example of using for/of loop

var myArray = [
    {id: 1, name: 'John', age: 12},
    {id: 2, name: 'Jane', age: 14},
    {id: 3, name: 'Martin', age: 13},
    {id: 4, name: 'Katie', age: 17},
    {id: 5, name: 'Louis', age: 11}
];

for (let profile of myArray) {
    console.log(profile.name)
}

/*
Output:
  John
  Jane
  Martin
  Katie
  Louis
*/

3. forEach()

The forEach() is an array’s method that uses a callback function to include any custom logic to the iteration. In other words, forEach() will execute the provided callback function once for each array element.

The forEach() method has the following syntax:

array.forEach(callback(currentValue [, index [, array]])[, thisArg]);
  • callback — refers to the callback function that takes up 3 arguments:
  1. currentValue — the data/value of the current element
  2. index (optional) —the array index of the current element
  3. array (optional) —the entire array object
  • thisArg (optional) — Value to be passed to the callback function which will be used as its this value.
  • Return — undefined

Note: There’s no way we can break a forEach() loop.

Example of using forEach() loop

// Example 1: Inline function
var myArray = [
    {id: 1, name: 'John', age: 12},
    {id: 2, name: 'Jane', age: 14},
    {id: 3, name: 'Martin', age: 13},
    {id: 4, name: 'Katie', age: 17},
    {id: 5, name: 'Louis', age: 11}
];

myArray.forEach(function(profile, index, myArr) {
    console.log(`Index: ${index}, Name: ${profile.name}`);
});

/*
Output:
  Index: 0, Name: John
  Index: 1, Name: Jane
  Index: 2, Name: Martin
  Index: 3, Name: Katie
  Index: 4, Name: Louis
*/


// Example 2: Standalone function
var myArray = [
    {id: 1, name: 'John', age: 12},
    {id: 2, name: 'Jane', age: 14},
    {id: 3, name: 'Martin', age: 13},
    {id: 4, name: 'Katie', age: 17},
    {id: 5, name: 'Louis', age: 11}
];

myArray.forEach((profile, index, myArr) => this.myfunction(profile, index, myArr));

myfunction = (profile, index, myArr) => {
    console.log(`Index: ${index}, Name: ${profile.name}`);
}

/*
Output:
  Index: 0, Name: John
  Index: 1, Name: Jane
  Index: 2, Name: Martin
  Index: 3, Name: Katie
  Index: 4, Name: Louis
*/

// Example 3: Using thisArg
this.totalAge = 0;

var myArray = [
    {id: 1, name: 'John', age: 12},
    {id: 2, name: 'Jane', age: 14},
    {id: 3, name: 'Martin', age: 13},
    {id: 4, name: 'Katie', age: 17},
    {id: 5, name: 'Louis', age: 11}
];

myArray.forEach(function(profile, index, myArr) {
    this.totalAge += profile.age;
}, this);   // If "this" wasn't being included in the arguement, this.totalAge will still be 0 

console.log(`Total Age: ${this.totalAge}`);

/*
Output:
  Total Age: 67
*/

4. while Loop

The basic while loop has the following syntax:

while (condition) {
    // code block to be executed
}
  • condition — defines when the loop will stop looping

Note: break statement can be used to “jump out” of a while loop.

Example of using while loop

var myArray = [
    {id: 1, name: 'John', age: 12},
    {id: 2, name: 'Jane', age: 14},
    {id: 3, name: 'Martin', age: 13},
    {id: 4, name: 'Katie', age: 17},
    {id: 5, name: 'Louis', age: 11}
];

var i = 0;
while(i < myArray.length) {
    console.log(myArray[i].name)
    i++
}

/*
Output:
  John
  Jane
  Martin
  Katie
  Louis
*/

5. do/while Loop

The do/while loop is in fact very similar to while loop. The only difference is that do/while loop will be triggered at least once regardless of the condition.

The basic do/while loop has the following syntax:

do {
    // code block to be executed
} while (condition)
  • condition — defines when the loop will stop looping

Note: break statement can be used to “jump out” of a do/while loop.

Example of using do/while loop:

var myArray = [
    {id: 1, name: 'John', age: 12},
    {id: 2, name: 'Jane', age: 14},
    {id: 3, name: 'Martin', age: 13},
    {id: 4, name: 'Katie', age: 17},
    {id: 5, name: 'Louis', age: 11}
];

var i = 0;
do {
    console.log(myArray[i].name)
    i++
} while(i < myArray.length)

/*
Output:
  John
  Jane
  Martin
  Katie
  Louis
*/

6. map()

At first glance, map() method is in fact very similar to forEach() method as it will also execute the provided callback function once for each array element. The only major difference is that map() method will create and return a new set of arrays based on the result of the callback function.

According to the documentation, one should use forEach() or for/of loop instead of map() method if you’re not using the newly created array it returns and/or you’re not returning a value in the callback function or else it will be considered as an anti-pattern.

The map() method has the following syntax:

var new_array = array.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])
  • callback — refers to the callback function that takes up 3 arguments:
  1. currentValue — the data/value of the current element
  2. index (optional) — the array index of the current element
  3. array (optional) — the entire array object
  • thisArg (optional) — Value to be passed to the callback function which will be used as its this value.
  • Return — a new set of array based on the return result of the callback function

Note: There’s no way we can break a map() method.

Example of using map() method:

// Example: Inline Function
var myArray = [
    {id: 1, firstName: 'John', lastName: 'Smith', age: 12},
    {id: 2, firstName: 'Jane', lastName: 'Brown', age: 14},
    {id: 3, firstName: 'Martin', lastName: 'Johnson', age: 13},
    {id: 4, firstName: 'Katie', lastName: 'Miller', age: 17},
    {id: 5, firstName: 'Louis', lastName: 'Wilson', age: 11}
];

var newArray = myArray.map(function(profile, index, myArr) {
    var newProfile = {
        'id': index + 1,
        'fullName': profile.firstName + ' ' + profile.lastName,
        'age': profile.age
    }

    return newProfile
})

newArray.forEach(function(profile, index, myArr) {
    console.log(profile.fullName)
});

/*
Output:
  John Smith
  Jane Brown
  Martin Johnson
  Katie Miller
  Louis Wilson
*/

// Example 2: Standalone function
myfunction = (profile, index, myArr) => {
    var newProfile = {
        'id': index + 1,
        'fullName': profile.firstName + ' ' + profile.lastName,
        'age': profile.age
    }

    return newProfile
}

var myArray = [
    {id: 1, firstName: 'John', lastName: 'Smith', age: 12},
    {id: 2, firstName: 'Jane', lastName: 'Brown', age: 14},
    {id: 3, firstName: 'Martin', lastName: 'Johnson', age: 13},
    {id: 4, firstName: 'Katie', lastName: 'Miller', age: 17},
    {id: 5, firstName: 'Louis', lastName: 'Wilson', age: 11}
];

var newArray = myArray.map((profile, index, myArr) => this.myfunction(profile, index, myArr))

newArray.forEach(function(profile, index, myArr) {
    console.log(profile.fullName)
});

/*
Output:
  John Smith
  Jane Brown
  Martin Johnson
  Katie Miller
  Louis Wilson
*/

So there you have it, I have already listed down all the 6 different approaches (together with somewhat detailed explanation) on how you can loop through an array in JavaScript.

I hope that this article will be able to assist you in building your awesome applications!

javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.

Create a Line Through Effect with JavaScript

In this post we are going to create an amazing line through effect, with help of CSS and lots of JavaScript. So, head over to your terminal and create a folder LineThroughEffect. Create three files -index.html, main.js and styles.css inside it.

Grokking Call(), Apply() and Bind() Methods in JavaScript

In this article, we will have a look at the call(), apply() and bind() methods of JavaScript. Basically these 3 methods are used to control the invocation of the function.