JavaScript loop

loops in JavaScript | AsgarTech

 In JavaScript, loops are used to execute a block of code repeatedly until a specific condition is met. There are mainly three types of loops in JavaScript: for, while, and do-while loops. Here are some examples:


for loop

The for loop is used when you know how many times you want to execute a block of code.


Syntax:


for (initialization; condition; increment) {

  // code to be executed

}


Example:


for (let i = 0; i < 5; i++) {

  console.log("The value of i is: " + i);

}


Output:

The value of i is: 0

The value of i is: 1

The value of i is: 2

The value of i is: 3

The value of i is: 4


while loop

The while loop is used when you do not know the number of times you want to execute a block of code, but you have a condition that needs to be satisfied.


Syntax:


while (condition) {

  // code to be executed

}


Example:


let i = 0;

while (i < 5) {

  console.log("The value of i is: " + i);

  i++;

}


Output:

The value of i is: 0

The value of i is: 1

The value of i is: 2

The value of i is: 3

The value of i is: 4


do-while loop

The do-while loop is similar to the while loop, but the block of code is executed at least once, even if the condition is false.


Syntax:


do {

  // code to be executed

} while (condition);



Example:

let i = 0;

do {

  console.log("The value of i is: " + i);

  i++;

} while (i < 5);


Output:


The value of i is: 0

The value of i is: 1

The value of i is: 2

The value of i is: 3

The value of i is: 4

check these all Courses blog----------->👇👇

Me


learn - java---------------> 👇


Learn-python------------>👇


Learn-html------------>👇


Learn-javascript------------>👇


Learn-c------------>👇


Thanks.





No comments: