Different types of While For Loop Javascript ES6

Javascript loops

In this blog, we will discuss different types of While For Loop Javascript ES6. Loops are used to repeatedly execute the same piece of code as long as a condition is satisfied. The primary idea behind a loop is to save time and effort by automating repetitive activities inside the software. Five distinct forms of loops are presently supported by JavaScript.

Different types of While For Loop Javascript ES6

  • while — cycles through a block of code until the specified condition evaluates to true.
  • do…while — cycles over a piece of code once, then evaluate the condition. If the condition is true, the statement will be repeated until the condition is no longer true.
  • for — iterates across a piece of code until the counter reaches a certain value.
  • for...in — cycles over an object’s attributes.
  • for...of — loops through iterable objects like arrays, strings, and so on.

While Loop

This is the most basic looping statement available in JavaScript.

The while loop iterates across a block of code as long as the stated condition is true. The loop is terminated as soon as the condition fails. The while loop has the following general syntax:

while(condition) {
// Logics
}

The loop in the following example will keep running as long as the variable i is less than or equal to 5. Each time the loop executes, the variable I will rise by one:

var i = 1;
while(i <= 5) {    
    console.log("The number is " + i );
    i++;
}

NOTE-: Keep in mind that the condition given in your loop must ultimately become false. Otherwise, the loop will continue to iterate indefinitely, resulting in an infinite loop. Forgetting to increase the counter variable is a typical blunder (variable I in our case).

do...While Loop

The do..while loop is a variety of the while loop in which the condition is evaluated at the conclusion of each loop iteration. A do-while loop executes a block of code once, then evaluates the condition; if the condition is true, the statement is repeated as long as the given condition is true. The do-while loop has the following general syntax:

do {
// Logics
}
while(condition);

The JavaScript code in the following example defines a loop that starts with i=1. It will then print the output and increase the value of the variable i by 1. After that, the condition is evaluated, and the loop will continue to run as long as the variable i is less than, or equal to 5.

var i = 1;
do {
    console.log("The number is " + i );
    i++;
}
while(i <= 5);

Difference Between while and do...while Loop

The while loop varies from the do-while loop in one key way: with a while loop, the condition to be evaluated is verified at the start of each loop iteration, thus the loop will never be performed if the conditional expression evaluates to false.

A do-while loop, on the other hand, will always run once even if the conditional expression evaluates to false since, unlike the while loop, the condition is evaluated at the conclusion of the loop iteration rather than at the beginning.

Different types of While For Loop Javascript ES6
While For Loop Javascript ES6 Working

The for Loop

The for loop is a control structure that repeats a block of code as long as a condition is satisfied. It’s usually used to repeat a piece of code a set number of times. Its syntax is as follows:

for(initializationconditionincrement) {
    // Logics
}

The example below shows how to create a loop that starts with i=1. The loop will be repeated until variable i’s value is less than or equal to 5. Each time the loop executes, the variable I will rise by one:

for(var i=1; i<=5; i++) {
    console.log("The number is " + i );
}

Flow chart:-

Different types of While For Loop Javascript ES6
While For Loop Javascript ES6

When it comes to iterating through an array, the for loop comes in handy. The example below will teach you how to print each item or element of the array 

// An array with some elements
var vechile = ["Car", "Bus", "Truck", "Cycle", "Train"];
 
for(var i=0; i<vechile.length; i++) {
    console.log("The elements of array" + vechile[i]);
}

 

ForEach loop

For this loop, let’s try something a little more complicated. Let’s pretend we have an array containing several objects:

const CarModel = [
  { name: 'BMW' },
  { name: 'SUZUKI' },
  { name: 'TATA' },
  { name: 'MAHINDRA' }
];

Let’s assume we wanted to traverse through each item in the CarModel using a for a loop. To access the values within CarModel, we would change the condition and use i as the numeric index.

CarModel.forEach((model, index) => {
  console.log(`i value: ${index} | CarModel Name:`,model);
});

Which should use? for or forEach?

  • forEach restricts the scope of the variable to the block.

The callback method in forEach allows you to maintain that variable within forEach’s scope, which is a nice feature. If you assign a variable outside and then utilize it within the forEach, the value of the outside variable is preserved.

  • With forEach, there’s a lower risk of making an error.

When you use the forEach function, you’re directly invoking the Array. prototype method on the array. You must set up a variable to increase I a condition to follow, and the actual increment when using a for a loop.

One of the primary reasons I’d utilize the for loop is if I needed to exit a loop quickly. You could use an if statement to verify if your criterion matches and then break out of the loop if you just wanted to retrieve a certain meal from your array. Because the forEach function iterates over each meal, performance concerns may arise.

The for...in Loop

The for-in loop is a particular variety of loops that iterates across an object’s attributes or an array’s items. The for-in loop has the following general syntax:

for(variable in object) {
    // Logics
}

The for-in loop’s loop counter, or variable, is a string, not a number. It holds the current property’s name or the current array element’s index.

The following example demonstrates how to loop over all of a JavaScript object’s properties.

//Object of Vechile
var vechileId = {"vechile": "Bus", "state": "Bihar", "Number": "BR 3609 DS"};
 
//Iterating through vechileObject
for(var id in vechileId) {  
    console.log( id + " = " + vechileId[id]); 
}

You may also loop through the items of an array.

// An array with some elements
var Employee = ["Ram", "Shyam", "Joya", "Rajshree", "Alex"];
 
// Loop through all the elements in the array 
for(var i in Employee) {  
        console.log(Employee[i]);
}

Note:- Note that the for-in loop should not be used to iterate through an array with important index order. A for loop with a numeric index is preferable.

The for...of Loop

The new for-of loop in ES6 makes it relatively easy to iterate over arrays or other iterable objects (such as strings). In addition, the loop’s function is run for each element of the iterable object.

The following example demonstrates how to use this loop to loop across arrays and strings.

// Iterating over string
let code = "Happy Coding!";

for(let char of code) {
    console.log(character); // H,a,p,p,y, ,C,o,d,I,n,g,!
}

Note-:Because objects are not iterable, the for…of the loop does not execute with them. The for-in loop may be used to iterate over the attributes of an object.

Hope you like our Types of While For Loop Javascript ES6 Blog. Please subscribe to our blog for an upcoming blog.

Happy Coding!

Read More: Promises in JavaScript | 10 Minute | 2021, Array Destructuring | Spread Operator | Rest Operator | Javascript, Best OS for Programming, Operators in Javascript

Leave a comment

Your email address will not be published.


*