{{announcement.body}}
{{announcement.title}}

For Loops in JavaScript: Native, forEach, and For-of

DZone 's Guide to

For Loops in JavaScript: Native, forEach, and For-of

In this article, we cover how to loop over array in JavaScript with a traditional, native loop, ES6's forEach method, and a for-of loop.

· Web Dev Zone ·
Free Resource

In this article, we're going to walk through the many different ways to loop through arrays in JavaScript, from the native approach many will be familiar with, to more recent (and readable) methods introduced in ES6 and later. 

Native For-Loop

JavaScript
 




xxxxxxxxxx
1


1
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
2

          
3
for(let i = 0; i < myArray.length; i++) {
4
    const currElem = myArray[i];
5
  
6
    console.log(`At index ${i}, our element is: ${currElem}`);
7
}



If you're new to programming, this might be a whole new concept. (If so, welcome! We're excited to have you. For those of you who've seen this more than a few times, feel free to skip to a later section.) In the above code block, we're first creating an array containing a "Hello, World!" message. 

Next, we're starting our for-loop. For-loops are defined by two sections, a header, where we specify how the loop will run, and the body, where we define what will happen at each iteration of our loop. The head of a for-loop contains three sections. The first defines a value, often a single letter, like i, that we want to start indexing our array at. The second defines a condition that will terminate our for-loop. The third performs an operation on i to move it to the next element in the array. 

In this case, i is 0, our terminating condition is i < 7 (the length of our array), and we add 1 to i to move it to the next index in our array. This tells our program that we want to look at each element in our array, starting at 0 (our first index) and ending at 6 (our last index).  

You may also like: Iteration Over Java Collections With High Performance.

In the body of our for-loop, we grab the element at i, assign it to a variable, currElem, and then print the index and the value of currElem to the console. Our output for this will be: 

Plain Text
 




x




1
At index 0, our element is: Hello,
2
At index 1, our element is: world!
3
At index 2, our element is: It's
4
At index 3, our element is: nice
5
At index 4, our element is: to
6
At index 5, our element is: meet
7
At index 6, our element is: you!



forEach Loop

Among the many helpful array methods introduced in ES6 is forEach. forEach takes a callback function as a parameter. The callback then takes a variable representing an individual element in an array as a parameter. Inside the body of the callback, we can create custom logic to perform an operation with or on each individual element of the array. 

Note: forEach does not return a new array of elements. If you mutate the element within the callback function, every element in the array will be mutated. (Take a look at map if you're looking to maintain state). 

Let's see a simple implementation of the method with an anonymous callback function as our argument: 

JavaScript
 




x



1
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
2

          
3
// the callback doesn't have to be an arrow function. You could 
4
// achieve the same result with the 'function' keyword
5
myArray.forEach(elem => {
6
    console.log(`Current element: ${elem}`); 
7
}



You can also use a predefined function as the callback, like this: 

JavaScript
 




xxxxxxxxxx
1


 
1
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
2

          
3
const printSomething = varToPrint => {
4
    console.log(`Current element: ${varToPrint}` 
5
}
6
                
7
myArray.forEach(printSomething)



Both of these implementations will result in a similar output to the one we had with our native for-loop: 

Plain Text
 




xxxxxxxxxx
1


 
1
Current element: Hello,
2
Current element: world!
3
Current element: It's
4
Current element: nice
5
Current element: to
6
Current element: meet
7
Current element: you!



If you need the index of the current element in the array, you can just add a second parameter to the callback function, like: 

JavaScript
 




xxxxxxxxxx
1


1
arr.forEach((elem, i) => {
2
  // some logic cooler than printing things out 
3
}



Here, i is the current index of the array, while elem is the current value at that index. 

For-of Loop

For those coming from a Java background, JavaScript's for-of loop will be pretty similar syntactically to an enhanced for-loop (though it's not so "enhanced" when you look at its actual performance). To me, for-of is the most readable option that the language offers:

JavaScript
 




x


 
1
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
2

          
3
for(const elem of myArray) {
4
    console.log(`Current element: ${elem}`);
5
}



The syntax here is pretty straightforward. In the first half of the header, we declare a variable that represents an individual element in our array. We then use the of keyword followed by the array that we want to iterate through: "For every element of this array, do something." (The only implementation that would be more readable would be if in could replace of (*cough* Python), but objects own that keyword for loops in JavaScript, and if a preposition is the only thing I can complain about here, my life's not that hard.)


Further Reading


Topics:
web dev ,javascript ,for-loop ,foreach ,for-of ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}