Looping Statements in JS

M2-R5.1 · Chapter 6: JavaScript and Angular JS · 1 min read

JavaScript Looping Statements

Loops allow you to run a block of code multiple times.

JavaScript provides these main loops:

1.) while Loop

Used when you don’t know the exact number of repetitions, but repeat until a condition becomes false.

Syntax

while (condition) { 
// code 
} 

Example

let i = 1;
while (i <= 5){ 
document.write(i);
i++;
} 

2. for Loop

Used when you know how many times you want to run the loop.

Syntax

for (initialization; condition; increment) {

// code

}

Example – print 1 to 5

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

document.write(i);

}