Languages
[Edit]
EN

JavaScript - for...in vs for...of

3 points
Created by:
Giles-Whittaker
739

In this article, we would like to show you the difference between for...in and for...of statements in JavaScript.

Quick solution:

for...infor...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:

Syntax:

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).

 

Practical example

Edit

In this section, we present a practical example of the difference between for...in and for...of while iterating an array.

1. for...in - iterates over object property names (properties + indexes).

Edit

1.1: array example

Each array is object too, so that statement is able to iterate over arrays.

Note:

Under this question we've described why shouldn't You use for…in statement to iterate arrays.

1.2. object example

2. for...of - iterates over iterable object values.

Edit

 

See also

Edit
  1. JavaScript - for...in statement

  2. JavaScript - for...of statement

  3. JavaScript - why shouldn't I use for…in statement to iterate arrays?

References

Edit
  1. for...in - JavaScript | MDN
  2. for...of - JavaScript | MDN

Alternative titles

  1. JavaScript - for...in and for...of differences
  2. JavaScript - difference between for...in and for...of
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join