Understanding for...in vs for...of statements in Javascript
Shivaansh Agarwal
Posted on June 22, 2021
Overview
- Differences
- Definition
- Syntax
- When to use for...in or for...of?
- Examples
- Further Reading
Differences
1. Definition
for...in:
The for...in
loop statement iterates over the enumerable properties of an object including the inherited enumerable properties in an arbitrary order except the keys that are of type Symbol
.
Enumerable properties
are those properties whose internal enumerable
flag is set to true.
The following properties a,b,c are enumerable by default:
const obj1 = {a:1, b:2};
obj1.c = 3;
The property defined using Object.defineProperty by default are not enumerable:
const obj2 = {};
Object.defineProperty(obj2, 'a', {
value: 42
});
for...of:
The for...of
loop statement iterates over the values that the iterable object defines to be iterated over like Array
, String
. etc.
Some built in types such as Array
and Map
have a default iteration behaviour while Object
does not.
2. Syntax
for...in:
for (variable in object) {
statement
}
for...of:
for (variable in iterable) {
statement
}
3. When to use for...in or for...of?
for...in:
-
for...in
can used in scenarios where you want to iterate over properties of an Object to check the keys and their corresponding values. - Since
for...in
loop statement iterates over enumerable properties of an object in an arbitrary order it is not recommended to usefor..in
with an Array where index order is important. It is because there is no guarantee thatfor...in
will return indexes in any particular order. - If you want to loop over values of an array consider using
for
with numeric index,Array.prototype.forEach
,for...of
.
for...of:
- To be used to iterate over iterable objects.
-
for...of
can be iterated overString
,Array
,TypedArray
,Map
,Set
, arguments object of a function,DOM Collection
,generators
, other iterable objects.
2. Example
Further Reading:
Following are the list of resources for further deep exploration:
Posted on June 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 28, 2024