All About Loops in JavaScript

The word ‘loop’ is defined as a shape produced by a curve that bends around and crosses itself. In computer programming world, loop is used in the same context. Loops are one of the important features of a programming language, as they take care of repetitive tasks.

Definition of loop

A loop is a sequence of instructions that are continually repeated unless it meets certain conditions. In other words, it lets us execute an instruction or group of instructions multiple times.

The different kinds of loops provided in JavaScript are:

    • while loop
    • do…while loop
    • for loop
    • for…in loop
    • for…of loop

We will also look into two array methods that we can use for iteration:

    • forEach( )
    • map( )

while loop

The while loop executes a block of code repeatedly as long as the condition is true. The loop ends when the condition becomes false.

Syntax:

Example:

do..while loop

The do..while loop executes a block of code once, before checking if the condition is true/false. Then, the block of code is executed repeatedly as long as the condition is true. So, the code executes at least once in this loop even when the condition is false, as the condition is checked at the end of the loop.

Syntax:

Example:

for loop

The for loop is a statement that has three optional expressions to perform repeated execution of a block of code. Initialization is where we initialize a new variable. Condition is where the condition is tested before every iteration and Final-Expression is what is used to increment or decrement a variable.

Syntax:

Example:

for..in loop

The for..in statement loops through the Enumerable properties of objects. Enumerable properties are those properties whose internal enumerable flags are set to true. The propertyIsEnumerable method lets us check if any property is enumerable, which means they are able to be counted by one-to-one correspondence with the set of all positive integers. This method returns a boolean.

Syntax:

Example:

Array iteration using for..in

Since Arrays are objects, too, we can use a for..in statement to iterate them. Indexes of arrays are the enumerable properties like Object keys are for objects.

Example:

Note: We can iterate an Array using the for..in loop, however It is not recommended to do so because the for..in loop does not guarantee an order of iteration. The for..in statement loops through an Object’s values in an arbitrary order, which means this is not an issue with Object as the values are normally not in sequential order. However, for Arrays, it is important that the iteration happens in a sequence.

String iteration using for..in

As each character in a string has an index, we can use the for..in to loop through them.

Example:

for..of loop

The for..of loop is fairly new. It was first introduced in JavaScript’s ES6. This loop iterates over objects like Array, String, Map, Set and more. Any element with Symbol.iterator property is an iterable object. As Objects do not have this Symbol.iterator property, we cannot use for..of statement to loop through them.

Syntax:

Array Iteration using for..of

String Iteration using for..of

Object iteration using for..of

forEach ( )

The forEach ( ) is an Array method that iterates over each element of the Array and executes a callback function. The parameters passed into the callback function includes the value of the current element, array index of the current element, and also the array itself. There is also a fourth parameter that we can specify- the thisValue, it is used as the ‘this’ reference when executing callback. The first parameter is required whereas the last three are optional.

Syntax:

Example:

Note:  We cannot end or break a forEach loop. The only way to do so is by throwing an exception, which is not preferable. But if we need to use ‘break’ in our code, we should instead use:

        • for loop or
        • for..of loop

map ( )

Another Array method, called map ( ) is a method that iterates over each element of the Array. This method creates a new Array with the results of the callback function that executes on each element of the old Array. The parameters passed into the map method is exactly the same as that of the forEach method – currentValue, index, array and thisArg.

Syntax:

Example:

Difference between forEach( ) and map( )

  1. A forEach method does not return anything (undefined) whereas map method returns a new Array of the same size.
  2. A forEach method mutates the original Array i.e it changes the original Array when it executes the callback function on the elements whereas map does not mutate the original Array and returns a new Array.
  3. As map method returns a new Array, it is possible to chain other Array methods like filter( ),  reduce ( ) etc. whereas we cannot chain other methods with forEach method.

Conclusion: When to use which loop

while loop:  When we do not know ahead of time how many times we need to repeat the loop. 

do..while loop:  When we want the code to execute at least once even when the condition is false.

for loop:  When we know ahead of time exactly how many times we need to repeat the loop.   

for..in loop:  When we want to loop through Object properties.

for..of loop: When we want to iterate objects like Array, String, Map, Set etc.

forEach ( ): When it is not required to return a new Array.

map ( ): When it is required to return a new Array or chain other methods.

Related Posts