EN
JavaScript - for...in vs for...of
3 points
In this article, we would like to show you the difference between for...in
and for...of
statements in JavaScript.
Quick solution:
for...in | for...of |
---|---|
The for...in loop is used to iterate over enumerable and non-Symbol properties. | The for...of loop is used to iterate over iterable objects (such as: strings, arrays, maps, sets, user-defined iterables, etc.). |
Syntax: xxxxxxxxxx 1 const object = {a: 1, b: 2, c: 3}; 2 3 for (const key in object) { 4 console.log(`${key}: ${object[key]}`); 5 } |
Syntax: xxxxxxxxxx 1 const array = ['a', 'b', 'c']; 2 3 for (const item of array) { 4 console.log(item); 5 } |
Iterates over object property names. | Iterates over iterable object values. |
Advice: Shouldn't be used to iterate over arrays (it may lead to mistakes). | |
Available in ES3, ES5, ... (may be even older than ES3). | Introduced in ES6 (2015). |
In this section, we present a practical example of the difference between for...in
and for...of
while iterating an array.
1.1: array example
Each array is object too, so that statement is able to iterate over arrays.
xxxxxxxxxx
1
const array = ['a', 'b', 'c'];
2
3
array['D'] = 'd'; // custom property (not index!!!)
4
array['E'] = 'e'; // custom property (not index!!!)
5
6
for (const element in array) {
7
console.log(element);
8
}
Note:
Under this question we've described why shouldn't You use for…in statement to iterate arrays.
1.2. object example
xxxxxxxxxx
1
const object = {'0': 'a', '1': 'b', '2': 'c'};
2
3
object['D'] = 'd'; // custom property (not index!!!)
4
object['E'] = 'e'; // custom property (not index!!!)
5
6
for (const element in object) {
7
console.log(element);
8
}
xxxxxxxxxx
1
const array = ['a', 'b', 'c'];
2
3
array['D'] = 'd'; // custom property (not index!!!)
4
array['E'] = 'e'; // custom property (not index!!!)
5
6
for (const element of array) {
7
console.log(element);
8
}