Archie  Clayton

Archie Clayton

1571644029

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

What is GEEK

Buddha Community

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

AKRAM ALEEMING

1571645388

Awesome

Lowa Alice

Lowa Alice

1624406400

JavaScript Loops Tutorial

JavaScript loops made simple.

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=s9wW2PpJsmQ&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=8
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #loops #javascript loops #javascript loops tutorial

Lowa Alice

Lowa Alice

1624388400

JavaScript Arrays Tutorial. DO NOT MISS!!!

Learn JavaScript Arrays

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=oigfaZ5ApsM&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=4
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#arrays #javascript #javascript arrays #javascript arrays tutorial

Alverta  Crist

Alverta Crist

1590399238

How To Loop Through An Array In JavaScript

The easiest way to use for loop and forEach array method.

#javascript #javascript array #looping array #morioh

6 Ways to Add Items to an Array in JavaScript

There are various ways to add or append an item to an array. We will make use of pushunshiftspliceconcatspread and index to add items to array. Let’s discuss all the 6 different methods one by one in brief.

The push() method

This method is used to add elements to the end of an array. This method returns the new array length.

const movies = ['Avengers', 'Iron-man', 'Thor'];

const newLength = movies.push('Hulk'); 

console.log(movies); // ['Avengers', 'Iron-man', 'Thor', 'Hulk'];

console.log(newLength); //4

We can also add multiple values with push method.

const movies = ['Iron-man', 'Thor']; 

movies.push('Avengers', 'Deadpool', 'Hulk');

console.log(movies); 
// ["Iron-man", "Thor", "Avengers", "Deadpool", "Hulk"]

The unshift() method

The unshift() method is used to add elements at the beginning of an array. This method returns the new array length.

const cars = ['Audi', 'BMW', 'Jaguar']; 

const newLength = cars.unshift('Mercedes'); 
console.log(newLength ); // 4 
console.log(cars); // ['Mercedes', 'Audi', 'BMW', 'Jaguar']

We can also add multiple values with unshift() method.

const cars = ['Audi', 'Jaguar']; 

cars.unshift('Mercedes', 'Tesla'); 
console.log(cars); // ['Mercedes', 'Tesla', 'Audi', 'Jaguar']

#arrays #web-development #javascript-tips #javascript #javascript-development

Terry  Tremblay

Terry Tremblay

1602154740

Fill and Filter in Array in JavaScript

By the word Array methods, I mean the inbuilt array functions, which might be helpful for us in so many ways. So why not just explore and make use of them, to boost our productivity.

Let’s see them together one by one with some amazing examples.

Array.fill():

The _fill()_ method changes all elements in an array to a static value, from a start index (default _0_) to an end index (default _array.length_). It returns the modified array.

In simple words, it’s gonna fill the elements of the array with whatever sets of params, you pass in it. Mostly we pass three params, each param stands with some meaning. The first param value: what value you want to fill, second value: start range of index(inclusive), and third value: end range of index(exclusive). Imagine you are going to apply this method on some date, so that how its gonna look like eg: array.fill(‘Some date’, start date, end date).

NOTE: Start range is inclusive and end range is exclusive.

Let’s understand this in the below example-

//declare array
var testArray = [2,4,6,8,10,12,14];

console.log(testArray.fill("A"));

When you run this code, you gonna see all the elements of testArray will be replaced by 'A' like [“A”,"A","A","A","A","A","A"].

#javascript-tips #array-methods #javascript-development #javascript #arrays