How to loop over arrays and objects in JavaScript

Updated: 07-Aug-2024 / Tags: Javascript Lang Reference / Views: 100 - Author: George

Introduction

Hi guys.
The most common thing that i do when i code in JavaScript is to loop through arrays and objects. So in this article we are gonna see how to do that by using the for...of loop, the for...in loop, and the foEarch() method.

Loop through an array

Let's see first how to loop through an array.

Using the for...of loop

Let's start with a basic example of the for...of loop, and loop through the names array.

let names = ["George", "Peter", "Betty", "Susan"];
for(let name of names){
	console.log(name);
}
/*
	Will output: George Peter Betty Susan
*/

Let's explain the for...of loop.

  • The for...of loop is used in JavaScript to iterate over the values of an array, string, or map.
  • The syntax is: for (variable of array)
  • Inside the parentheses first we declare a variable (let name). The name variable will give us access to every item in the array, in our case in every name. That means when the loop first starts, in the first iteration the name variable will hold the value "George", in the second iteration the name variable will hold the value "Peter", and so on.
  • After we declare the variable we say (... of names). We pass in the loop, after the of keyword, the array that we want to loop over.

Most of the times we are going to do some sort of comparison inside the loop using an if statement.

let numbers = [1, 5, 14, 34];
for(let number of numbers){
	if(number > 14 ){
		// do something
	}	
}
  • In the above example we have an array of numbers, and inside the loop we check if there is a number inside the array that is greater than 14.

Using the forEach method

The forEach() method is a built-in function in JavaScript that allows you to loop through an array and perform a action on each element. It takes a callback function as an argument, which is executed for each element of the array.
Let's see how we use it.

Again we will use the names array.

let names = ["George", "Peter", "Betty", "Susan"];

To use the forEach() method we have to invoke it on an array. So we have to call it on the names array.

names.forEach();

The forEach() method takes as an argument a callback function.

names.forEach(function(){});

The callback function takes two arguments.

names.forEach(function(item, index){});

The first argument,(item), will give us access to the values,(names), and the second argument,(index), will give us the index of the current value. Of course we can name those two variables whatever we like.

To access the values from the names array, we have to go inside the body of the callback function, and let's just do a simple console.log() on the item variable.

names.forEach(function(item, index){
	console.log(item);
});
/*
	Will output: George Peter Betty Susan
*/

If we want to access each index, we use the index variable.

names.forEach(function(item, index){
	console.log(index);
});
/*
	Will output: 0 1 2 3
*/

We can write the above code in a single line using as a callback an arrow function.

names.forEach((item, index) => console.log(index));

Loop through an object

Let's see now how we loop over an object.

Using the for...of loop

We will create a user object which we'll use in the example that follows.

let user = {
	name: "Peter",
	lastname: "Parker",
	age: 22,
	"fav-foods": ['Pizza', 'Burgers', 'Pasta']
}

We will structure the for...of method a little bit differently than the one that we used to loop through the names array.

for(let [property, value] of Object.entries(user)){
	console.log(property);
	// Will output: name lastname age fav-foods

	console.log(value);
	// Will output: Peter Parker 22 ['Pizza', 'Burgers', 'Pasta']
}

Let's explain the for...of function.

  • I am going to start backwards, and explain the second part of the loop, which is the Object.entries(user) function, in this way the first part let [property, value] will make more sense.
  • The Object.entries() build in JavaScript function takes an object as an argument and converts it to an array of arrays, and we can use the data as key value pairs.
    In our case the Object.entries(user) returns the following array:
    [
    	['name', 'Peter'],  
    	['lastname', 'Parker'], 
    	['age', 22], 
    	['fav-foods', ['Pizza', 'Burgers', 'Pasta']]
    ]

    You see that every sub-array contains the object's property and value.

  • So to access the object's properties and values we declare in the first part two variables inside square brackets
    let [property, value]. The first variable will access the object's properties, and the second the object's values.
  • That is how we can loop over an object using the for...of loop. Let me say that basically we loop through an array an not an object, that's why the for...of loop works.

Using the for...in loop

Now we are gonna see how to loop through an object using the for...in loop. Actually the for...in loop iterates over an object's properties. We are going to see this, in this example, by using again the user object.

let user = {
	name: "Peter",
	lastname: "Parker",
	age: 22,
	"fav-foods": ['Pizza', 'Burgers', 'Pasta']
}

The for...in loop has the same structure as the for...of loop, but instead of the keyword of, we have the keyword in. The for...in loop behaves different, it iterates only over the object's properties.

for(let property in user){
	console.log(property);
	// Will output: name lastname age fav-foods

	console.log(user[property]);
	// Will output: Peter Parker 22 ['Pizza', 'Burgers', 'Pasta']
}
  • The let property variable that we declare in the first part of the loop, will give us access on the user object properties. As you can see in line 8, when we output the property variable it gives us the property names.
  • If we want the object's values we have to use the property variable as a key on the user object user[property]. So in line 11, we get the user object's values.

Summary

In this quick tutorial we saw how to use the for...in, the for...of, and the forEach() method, to loop over arrays and objects. I will say that it is an easy task, if you pay attention on the details.

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any errors, so i can update the page with the correct code.

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal