JavaScript Loops

Loop is a control structure that allows you to execute a block of code multiple times. There are three types of loops in JavaScript: for loop, while loop, and do-while loop.

Js For Loop

For loop: The for loop is used to execute a block of code a specified number of times. It has three parts: initialization, condition, and increment/decrement. Syntax: for (initialization; condition; increment/decrement) { // code here }

Here's an example of for loop in JavaScript

// JavaScript for loop code example
for (let i = 0; i < 5; i++) {
    console.log(i);
   }
   
/*
Output:
0
1
2
3
4
*/
            

While Loop

While loop: The while loop is used to execute a block of code as long as the specified condition is true. Syntax: while (condition) { // code here };

Here's an example of while loop in JavaScript


// JavaScript while loop code example
let i = 0;

while (i < 5) {
  console.log(i);
  i++;
  }
/*
Output:

0
1
2
3
4
*/
              

Do While Loop

The do-while loop is similar to the while loop, except that the code block is executed at least once, even if the condition is false. Syntax: do { // code to be executed } while (condition);

Here's an example of do while loop in JavaScript

// JavaScript do while loop code example

let i = 0;

do {
  console.log(i);
  i++;
   } while (i < 5);
/*
Output:

0
1
2
3
4
*/

Conclusion

Overall, JavaScript loops are used to repeatedly run a block of code - until a certain condition is met. When developers talk about iteration or iterating over, say, an array, it is the same as looping.

Now challenge yourself, click the link below to practice!

  • https://codepen.io/pen/