All Articles

For...of vs for...in loops in JavaScript

The loop is an instruction that repeats until a specified condition is reached. It is mainly using for executing a block of code multiple of times.

For.. of and for..in are introduced in ES6.

for/of - Loops through the values of an iterable object

const cars = ["Audi", "bens", "tesla"];
for (const item of cars) {
  console.log(item);
}

The output is,

Audi
bens
tesla

Strings are also of itertable type, so you can use for…of on strings:

let carName = "Audi";
for (let char of carName) {
  console.log(char);
}

The output is,

A
u
d
i

You can also iterate over maps, sets, generators, DOM node collections and the arguments object available inside a function.

for/in - loops through the properties of an object.

const cars = { 0: "Audi", 1: "bens", 2: "tesla" };
for (const item in cars) {
  console.log(cars[item]);
}

The output is,

Audi
bens
tesla