Loop in javascript with example

Loop in javascript with example 


Cover Image of Loop in javascript with example
Cover Image of Loop in javascript with example 


In JavaScript, you can create loops using the for, while, and do-while statements. Here are examples of each type of loop:


Here's an explanation of each of the three types of loops in JavaScript:


for loop:

A for loop is a control flow statement that allows you to repeat a block of code a certain number of times. The loop has three components: the initialization statement, the condition statement, and the increment/decrement statement.


Syntax:


for (initialization statement; condition statement; increment/decrement statement)

 {

  // code block to be executed

}



The initialization statement is executed only once before the loop starts. The condition statement is evaluated before each iteration of the loop, and if it is true, the code block is executed. The increment/decrement statement is executed after each iteration of the loop. The loop continues until the condition statement becomes false.



while loop:

A while loop is similar to a for loop, but it doesn't have an initialization or an increment/decrement statement. It only has a condition statement. The loop will continue to execute as long as the condition is true.


Syntax:


while (condition statement)

 {

  // code block to be executed

}


The condition statement is evaluated before each iteration of the loop, and if it is true, the code block is executed. If the condition becomes false, the loop stops.



do-while loop:

A do-while loop is similar to a while loop, but it executes the code block at least once before checking the condition.


Syntax:

javascript

do {

  // code block to be executed

while (condition statement);


The code block is executed once before the condition statement is evaluated. If the condition is true, the loop will continue to execute. If the condition is false, the loop stops.


 loops are used when you know the number of times you want to repeat a block of code, while loops are used when you don't know how many times you want to repeat a block of code, and do-while loops are used when you want to execute a block of code at least once before checking a condition.



Loop in javascript with example 


for loop: This loop is used when you know the number of iterations you want to perform.

Example:

for loop example image
for loop example image 



while loop: This loop is used when you don't know how many times the loop needs to be executed, but you have a condition to check before each iteration.


Example:
While Loop in javascript with example
While Loop in javascript with example 


do-while loop: This loop is similar to the while loop, but it executes the loop body at least once before checking the condition.

Example:

Do while Loop in javascript with example image
Do while Loop in javascript with an example image



Post a Comment

Previous Post Next Post