Loops are used when we need to execute one or more statements repeatedly within the same scope. There are three types of loops: while, for, and do-while loops, which we’ll cover in this lesson. Each type of loop has its own syntax and use cases, and understanding how to use loops effectively can help simplify and streamline our code.

The while loop

A while loop is often preferred when the number of loop iterations is unknown in advance, and the loop continues until a certain condition is met. The advantage of a while loop is that it allows for greater flexibility in controlling the termination of the loop based on the condition that is evaluated at runtime.

The body of the while loop can be a single statement or a block of statements enclosed in curly braces. If we want to execute more than one statement in the body, we must enclose them in a block statement. Here’s the general syntax.

Get hands-on with 1200+ tech skills courses.