Techscrypt

For loops in Javascript

javascriptnodejs

There are multiple ways to use a for loop in javascript

Traditional for loop


for (<define variable>; <condition>; <increment>) {}

for (let i = 0; i < 10; i++) {}

This is a traditional for loop, where a variable is defined and initialized and iterations are run
as long as the condition i < 10 is satisfied. Iterations stop when the condition is no longer satisfied.

The for...in loop


for (const property in object) {}

The for...in statement iterates over all enumerable properties of an object that are keyed by strings
(ignoring ones keyed by Symbols), including inherited enumerable properties.

This loop is used to iterate over properties in an object. So using this loop over an array would still work,
but it is not recommended and it is important to understand the difference between for...in vs for...of.

Note: for...in should not be used to iterate over an Array where the index order is important.

The for...of loop


for (const element of array1) {}

The for...of statement creates a loop iterating over iterable objects. This is the recommended loop to use with arrays.
Each iteration element is the value from the iterable.

The for await...of loop


for await (variable of iterable) {}

The for await...of statement creates a loop iterating over async iterable objects as well as on sync iterables.
This loop is similar to the for...of loop, but works with async iterables

Difference between for...in and for...of

The for...of loop fetches the values of the array elements as expected


const list = ['a','b','c'];
for (const v of list) { console.log(v) }

// Output
a
b
c

Using a for...in loop with arrays can cause unexpected behavior because looks at the object properties and not the values


const list = ['a','b','c'];
for (const v in list) { console.log(v) }

// Output
0
1
2

References

  1. MDN for Loop
  2. MDN for...in Loop
  3. MDN for...of Loop
  4. MDN for await...of Loop

Subscribe to the Newsletter

We will only use your email address to send out the weekly newsletter with the latest updates from Techscrypt.

* indicates required