There are multiple ways to iterate through objects, arrays, and DOM elements in JavaScript. Traditionally, the basic for
loop was used to perform an iteration. But, lately, the other iteration methods have become more popular.
In this article, I'll describe the difference between the for...of
and for...in
statements, two of the most commonly used iteration methods in modern JavaScript. Both these statements are used for looping purposes. The main difference between them is what they iterate over.
for...in
Loop
The for...in
statement iterates over all enumerable properties of an object including the inherited enumerable properties in no particular order:
const book = {
title: 'JavaScript for Beginners',
price: '$9.99',
year: 2018,
pubisher: 'Amazon, Inc.'
}
// iterate over the object
for (const key in book) {
console.log(`${key} --> ${book[key]}`)
}
// title --> JavaScript for Beginners
// price --> $9.99
// year --> 2018
// pubisher --> Amazon, Inc.
To skip the object inherited properties, just use the hasOwnProperty()
method:
for (const key in book) {
if (book.hasOwnProperty(key)) {
console.log(`${key} --> ${book[key]}`)
}
}
for...of
Loop
The for...of
statement loops over the values of iterable objects like arrays, strings, maps, sets, NodeLists, and similar. It doesn't work for objects because they are not iterable.
Here is an example:
const names = ['Alex', 'Emma', 'Atta', 'John']
// iterate over names
for (const name of names) {
console.log(`Hey ${name}!`)
}
// Hey Alex!
// Hey Emma!
// Hey Atta!
// Hey John!
Rule of Thumb: Always use the for...in
loop to iterate over objects. For all kinds of iterable objects in JavaScript, for...of
is the way to go!
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.