for ... in vs for ... of
Written byPhuoc Nguyen
Created
08 Sep, 2020
Category
JavaScript
#Differences
-
The values iterated on the
`for ... in`
and`for ... of`
statements are different.`for ... in`
iterates over the enumerable property keys of object. Whereas`for ... of`
iterates over the values of the numeric properties of object.jsconst list = ['a', 'b', 'c'];for (let i in list) {console.log(i); // '0', '1', '2'}for (let i of list) {console.log(i); // 'a', 'b', 'c'} -
Unlike
`for ... in`
,`for ... of`
does not support plain objects:jsconst person = {firstName: 'Foo',lastName: 'Bar',age: 42,};// TypeError: `person` is not iterablefor (let k of person) {...}It is because a plain object is not iterable. To fix that, we can use the`Object.keys()`
method to iterate on the object properties:jsfor (let k of Object.keys(person)) {console.log(k, ':', person[k]);}// firstName: Foo// lastName: Bar// age: 42 -
`for ... of`
supports iterating over a Unicode string.jsconst msg = 'Hell😀 W😀rld';// for ... infor (let i in msg) {console.log(msg[i]);}// Output:// 'H', 'e', 'l', 'l', '�', ' ', 'W', '�', '�', 'r', 'l', 'd'// for ... offor (let c of msg) {console.log(c);}// Output:// 'H', 'e', 'l', 'l', '😀', ' ', 'W', '😀', 'r', 'l', 'd' -
`for ... of`
loop can wait for an async task to complete in each iteration via the`await`
keyword:jsfor await (... of ...) {...}
#Good practices
-
It is not recommended to add a custom method to primitive objects such as
`Array`
,`Boolean`
,`Number`
,`String`
, etc. Since`for ... in`
statement loops over the enumerable properties, it will include new methods which are added to the prototype.jsArray.prototype.isEmpty = function () {return (this.length = 0);};const a = ['cat', 'dog', 'mouse'];for (let i in a) {console.log(i); // '0', '1', '2', 'isEmpty'} -
jsconst addressBook = new Map();addressBook.set('Foo', '111-222-333');addressBook.set('Bar', '444-555-666');for (const [name, phone] of addressBook) {console.log(name, ':', phone);}// Foo: 111-222-333// Bar: 444-555-666
#Good to know
By default, all properties of an array or object will appear in
`for ... in`
. However, this behavior is avoidable.
Using `Object.defineProperty`
can decide whether a property is enumerable or not.js
let person = {
firstName: 'Foo',
lastName: 'Bar',
};
// The 'age' property is not enumerable
Object.defineProperty(person, 'age', {
value: 42,
enumerable: false,
});
for (let i in person) {
console.log(i); // 'firstName', 'lastName'
}
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn