JavaScript Code


JavaScript Loops


Loops

Loops are used to execute a block of statements multiple times. The number of times the loop has to run can depend on a condition, or the number of elements in the given collection.

JavaScript supports following loop statements .

  • for loop is used to execute a block of code based on a condition.
  • for…in loop is used to execute a block of code for each key in the key-value pairs of the given object.
  • for…of loop is used to execute a block of code for each item in the given iterator.
  • while loop is used to execute a block of code based on a condition.
  • do-while loop is used to execute a block of code based on a condition, but the block of code runs at-least once.

We can break the loop or continue with the next iteration using following statements.

  • break is used to break the loop.
  • continue is used to continue with the next iteration of the loop.

Examples

for loop

const fruits = ["apple", "banana", "cherry"];
for ( let index = 0; index < fruits.length; index++ ) {
    console.log(fruits[index]);
}

for…in loop

const fruits = ["apple", "banana", "cherry"];
for (let index in fruits) {
    console.log(fruits[index]);
}

for…of loop

const fruits = ["apple", "banana", "cherry"];
for (let item of fruits) {
    console.log(item);
}

while loop

const fruits = ["apple", "banana", "cherry"];
let index = 0;
while ( index < fruits.length ) {
    console.log(fruits[index]);
    index++;
}

do-while loop

const fruits = ["apple", "banana", "cherry"];
let index = 0;
do {
    console.log(fruits[index]);
    index++;
} while ( index < fruits.length );

break

const fruits = ["apple", "banana", "cherry"];
for (let index in fruits) {
    if (index == 1) {
        break;
    }
    console.log(fruits[index]);
}

continue

const fruits = ["apple", "banana", "cherry"];
for (let index in fruits) {
    if (index == 1) {
        continue;
    }
    console.log(fruits[index]);
}