For Loops in JavaScript: Native, forEach, and For-of
Join the DZone community and get the full member experience.
Join For FreeIn 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
xxxxxxxxxx
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
for(let i = 0; i < myArray.length; i++) {
const currElem = myArray[i];
console.log(`At index ${i}, our element is: ${currElem}`);
}
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:
x
At index 0, our element is: Hello,
At index 1, our element is: world!
At index 2, our element is: It's
At index 3, our element is: nice
At index 4, our element is: to
At index 5, our element is: meet
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:
x
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
// the callback doesn't have to be an arrow function. You could
// achieve the same result with the 'function' keyword
myArray.forEach(elem => {
console.log(`Current element: ${elem}`);
}
You can also use a predefined function as the callback, like this:
xxxxxxxxxx
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
const printSomething = varToPrint => {
console.log(`Current element: ${varToPrint}`
}
myArray.forEach(printSomething)
Both of these implementations will result in a similar output to the one we had with our native for-loop:
xxxxxxxxxx
Current element: Hello,
Current element: world!
Current element: It's
Current element: nice
Current element: to
Current element: meet
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:
xxxxxxxxxx
arr.forEach((elem, i) => {
// some logic cooler than printing things out
}
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:
x
let myArray = ["Hello,", "world!", "It's", "nice", "to", "meet", "you!"];
for(const elem of myArray) {
console.log(`Current element: ${elem}`);
}
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
- An Introduction to JavaScript/ES6 Arrow Functions/
- JS Array From an Array-Like Object
- Debug JavaScript in Production With Source Maps
Opinions expressed by DZone contributors are their own.
Comments