JavaScript Loops

Loops in JavaScript are used to execute a block of code more than once. This is done to avoid writing the code multiple times. The following are the loops in JavaScript:

  • while loop
  • do-while loop
  • for loop

The while loop

In the while loop, the block of code executes only when the condition is true. It executes if the condition is true. The following is the syntax of the while loop in JavaScript:

Let us see an example to implement the while loop in JavaScript:

Output

JavaScript while loop

The do-while loop

The do-while loop is the same as while, but the do-while executes the statement first and then the condition is tested. This would mean even in case of a false condition; the loop gets executed at least one time.

The following is the syntax of using the do-while loop in JavaScript,

The following is an example showing the usage of the do-while loop in JavaScript,

Output

JavaScript do-while loop

The for loop

The for loop is a loop that executes a specified number of times. Under this, initialize, test, and increment loop counter in a single line, unlike the while and do-while loop.

The syntax of for loop shows the usage of the loop counter, its initialization, as well as the condition:

Let us see an example to implement the for loop in JavaScript:

Output

JavaScript for loop

JavaScript - Decision Making Statements
JavaScript Comments
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading