For...of loop
For...of
loops are introduced in ES6 along with the iterable and iterator constructs. This new loop constructs replaces both the for...in
and for...each
loop constructs of ES5. As the for...of
loop supports the iteration protocol, it can be used on built-in objects such as arrays, strings, maps, sets, and so on, and custom objects that are iterables. Consider the following piece of code as an example:
const iter = ['a', 'b']; for (const i of iter) { console.log(i); } "a" "b"
The for...of
loop works with iterables and built-ins like arrays are iterables. If you notice, we are using const
instead of var
when we define the loop variable. This is a good practice because when you use const
, a fresh variable is created with a new binding and storage space. You should use const
over a var
declaration with the for...of
loop when you don't intend to modify the value of the loop variable inside the block.
Other collections...