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:
while (condition) { // Code block to be executed as long as condition is true }
Example:
let i = 0; while ( i < 5 ) { console.log( i ); i++; // Increment variable by 1 } // Output: 0, 1, 2, 3, 4
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:
do { // code block to be executed } while (condition);
Example:
let x = 0; do { x++; // Increment variable by 1 console.log( x ); } while ( x < 1 ); // Output: 1
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:
for ( initialization; condition; final-expression ) { // code block to be executed }
Example:
for( let i = 0; i < 5; i++ ) { console.log( i ); } //Output: 0, 1, 2, 3, 4
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.
var person = { age: 42 }; console.log( person.propertyIsEnumerable(‘age’) ); // Output: true
Syntax:
for ( variable in object ) { // Code block to be executed }
Example:
const obj = {a:1, b:2, c:3}; for( let val in obj ){ console.log( obj[ val ] ); } // Output: 1, 2, 3
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:
const names = ['Toby', 'Jim', 'Pam', ‘Stanley']; for (let i in names) { console.log( names[ i ] ); } // Output: Toby, Jim, Pam, Stanley
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:
const word = ‘Happy'; for (let i in word) { console.log(word[ i ]); } // Output: H, a, p, p, y
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:
for (variable of iterable) { // code block to be executed }
Array Iteration using for..of
const names = ['Tom', 'Jim', 'Pam']; for(let name of names){ console.log(name); } // Output: Tom, Jim, Pam
String Iteration using for..of
const greeting = 'Hello World'; for(let value of greeting){ console.log(value); } // Output: H, e, l, l, o, , W, o, r, l, d
Object iteration using for..of
const person = { firstName: 'James', lastName: 'Bond' }; for (let value of person) { console.log(value); } // Output: person is not iterable
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:
array.forEach(function(currentValue, index, arr) { // function body }, thisValue);
Example:
const names = ['Tom', 'Jim', 'Pam']; names.forEach(function(name) { console.log(name); }); // Output: Tom, Jim, Pam
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:
var newArray = oldArray.map(function( currentValue, index, array) { // function body }, thisArg);
Example:
const arr = [2, 4, 6, 8, 10]; let newArr = arr.map(function(num) { return num * 2; }); console.log(newArr); // Output: 4, 8, 12, 16, 20
Difference between forEach( ) and map( )
- A forEach method does not return anything (undefined) whereas map method returns a new Array of the same size.
- 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.
- 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.