Loop in JavaScript

Fahim Ahammed Firoz
2 min readFeb 23, 2021

A loop is a programming structure that repeats a sequence of instructions until a specific condition is met.
The purpose of loops is to repeat the same, or similar, code a number of times.

JavaScript (JS) support different kinds of loops:
1. for
2. while
3. do — -while
4. for — -in
5. for — -of

for loop in JS:

Syntax of for loop:

for(initial_Expression; condition_Expression; increment/decrement_Expression){
//statement
}

Description
1. initial_Expression — This expression is commonly used to create counters. Once the loop has finished it’s execution they are destroyed.
2. condition_Expression — Expression that is checked prior to the execution of every iteration. If it evaluates to true, the loop’s statement is executed. If it evaluates to false, the loop stops.
3. increment/decrement_Expression — Expression that is run after every iteration. Usually used to increment/decrement a counter.

Example 1:

for(let i=1; i<=100; i++){
console.log(i);
}

Example 2:

const array[] = {1, 2, 3, 4, 5};
for(let i=0; i<array.length; i++){
console.log(array[i]);
}

while loop in JS:

Syntax of while loop:

initial_Expression;
while(condition_Expression){
//statement
increment/decrement_Expression;
}

If the condition_Expression become false, statement within a loop stops executing and control passes to the statement following the loop.

Example:
let i = 1;
while(i<=100){
console.log(i);
i++;
}

Example 2:
const array[]={1,2,3,4,5};
let i=0;
while(i<array.length){
console.log(array[i]);
i++;
}

The while loop evaluates the test expression inside the parenthesis(). If the test expression is true, statements inside the body of loop are executed. Then, the test expression is evaluated again. The process goes on until the test expression is evaluated to false. If the test expression is false, the loop ends.

do — while loop in JS:

Syntax of do — while loop
initial_Expression;
do{
//statement
//increment/decrement_Expression
}
while(condition_Expression);

A do — while loop is similar to a while loop. But notice that the conditional expression appeares at the end of the loop. So the statement in the loop excutes once before the condition is tested.

Example 1:
let i = 1;
do{
console.log(i);
i++;
}
while(i<=100);

Example 2:
const array[]={1,2,3,4,5};
let i=0;
do{
console.log(array[i];
i++;
}
while(i<array.length);

while and do — while loop execution is also terminated on the basis of the test condition. The main difference between a while and do — while loop is in the while loop is entry contolled loop and do — while loop is exit controlled loop.

[N.B: Do not forget to incerase the variable used in the condition, otherwise the loop will never end.]

Follow me:

Thank you.

--

--

Fahim Ahammed Firoz

I am a hardworking, confident, enthusiastic Web developer and I want to utilize my knowledge and personal skills in Web Development.