A for loop repeats until a specified condition evaluates to false.
while statement
A while statement executes its statements as long as a specified condition evaluates to true.
do…while statement
The do...while statement repeats until a specified condition evaluates to false.
for…in statement
The for...in statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements.
for…of statement
The for...of statement creates a loop Iterating over iterable objects (including Array, Map, Set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
The for-of loop can be used to iterate over keys in an object.
continue and break keywords can be used with for-of loops.
You can use let instead of const too, if you reassign the variable inside the block.
Difference Between a for...of loop and a for...in loop
Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over.
for...in iterates over property names
for...of iterates over property values
Iterating With Index and Element
It can be difficult as the for-of loop was intended to iterate and list out the list of items. But we can do it with this method via the .entries() which will return an array of both index position and value.
We can also destructure the object in the loop to do something useful with it.
Iterating Objects
Object Keys
We can iterate over an object to get property names (keys) using Object.keys() .
Object Values
We can iterate over an object to get values using Object.values() .
Object Keys and Values
We can iterate over an object both keys and values using Object.entries() . This will return an array of arrays that have object key and value.
Iterating Maps
Maps iteration doesn’t require using entries() method.
forEach
forEach is a higher order function that requires another callback function to do something with values being iterated.
forEach loop can’t use break and continue keywords. It will always iterate over the whole object.
In each iteration, forEach passes three variables:
Array’s current value, index, and the array itself.