Javascript Loops

Pro Tips
0

 

JavaScript Loops

In JavaScript, loops are used to repeatedly execute a block of code until a certain condition is met. There are several types of loops in JavaScript:




1. For Loop:

A for loop is used when you know beforehand how many times the loop should run.

for (initialization; condition; iteration) {

    // code to be executed

}

Example: 👇

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

console.log(i);

}


2. While Loop:

A while loop is used when the number of iterations is not known beforehand, and the loop runs as long as a specified condition is true.

while (condition) {

    // code to be executed

}

Example:

let i = 0;

while (i < 5) {

    console.log(i);

    i++;

}

 

3. Do-While Loop:

Similar to the while loop, but the code block is executed at least once before the condition is tested.

do {

    // code to be executed

} while (condition);

Example:

let i = 0;

do {

    console.log(i);

    i++;

} while (i < 5);

4. For...In Loop:

Iterates over the enumerable properties of an object.

for (variable in object) {

    // code to be executed

}

Example:

const person = {

    name: 'John',

    age: 30,

    gender: 'male'

};

 

for (let key in person) {

    console.log(key + ': ' + person[key]);

}

5. For...Of Loop:

Introduced in ECMAScript 2015 (ES6), it iterates over iterable objects (arrays, strings, maps, sets, etc.).

for (variable of iterable) {

    // code to be executed

}

Example:

const fruits = ['apple', 'banana', 'orange'];

for (let fruit of fruits) {

    console.log(fruit);

}

When using loops, ensure that there's a way to exit the loop; otherwise, it will run infinitely, causing the browser or Node.js environment to become unresponsive. Always have a clear exit condition in your loops.

Tags

Post a Comment

0 Comments
Post a Comment (0)