javascript

Loops and Iteration


 

Loops and iterations in JavaScript are used to execute a block of code repeatedly. There are several types of loops available in JavaScript.

 

Loops:

 

1. For Loop 

It executes a block of code for a specific number of times.


Syntax:

// for loop
for (initialization; condition; increment/decrement) {
    // code to be executed
}

 

Example

// for loop
for (let i = 0; i < 3; i++) {
    console.log(i); // 0  1  2
}

 

2. While Loop

It executes a block of code while a specified condition is true.
 

Syntax:

// while loop
while (condition) {
    // code to be executed
}

 

Example:

// while loop
let i = 0;
while (i < 3) {
    console.log(i); // 0 1 2
    i++;
}

 

3. Do…while Loop


The code of block is executed once before the condition is checked.
 

Syntax:

// do-while
do{
    // code to be executed
}while(condition);

 

Example:

// do-while
let i = 0;
do {
    console.log(i);
    i++;
} while (i < 3); // 0 1 2

 

Iterators:

 

1. For…in loop

Iterates over the enumerable properties of an object.
 

Syntax:

// for...in loop
for (variable in object) {
    // code to be executed
}

 

Example:

// for...in loop
const person = {name: 'Wasif', age: 22, gender: 'male'};
for (let key in person) {
    console.log(key + ": " + person[key]);
}

 

2. For…of Loop

Iterates over iterable objects (arrays, strings, maps, sets, etc.).
 

Syntax

// for...of loop
for (variable of iterable) {
    // code to be executed
}

 

Example

// for...of loop
const skills = ['JavaScript', 'c++', 'python'];
for (let fruit of skills) {
    console.log(skills);
}