Categories
Programming

JavaScript loops cheat sheat

This cheat sheet provides a quick reference guide to the various loop types in JavaScript, including their syntax, descriptions,
and examples. Loops are an essential part of any programming language, including JavaScript. They allow you to execute a
block of code repeatedly, enabling you to automate repetitive tasks and iterate over data structures.

for loop

The for loop is used when the number of iterations is known in advance. It initializes a variable, checks a condition, and increments or decrements the variable value. The loop continues until the condition becomes false.

Syntax

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

Example

for (let i = 0; i < 5; i++) {
    console.log(i);
}

Output in console

0
1
2
3
4     

while loop

The while loop is used when the number of iterations is not known in advance. It executes the code block as long as the condition remains true.

Syntax

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

Example

let i = 0;

while (i < 5) {
    console.log(i);
    i++;
}

Output in console

0
1
2
3
4       

do-while loop:

The do-while loop is similar to the while loop, but it always executes the code block at least once before checking the condition.

Syntax

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

Example

let i = 0;

do {
        console.log(i);
        i++;
} while (i < 5);

Output in console

0
1
2
3
4       

for…in loop

The for…in loop iterates over the enumerable properties of an object.

Syntax

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

Example

const obj = { a: 1, b: 2, c: 3 }; // initiating a a const object

for (let key in obj) {
    console.log(`${key}: ${obj[key]}`);
}

Output in console

a: 1
b: 2
c: 3

for…of loop

The for…of loop is used to iterate over iterable objects, such as arrays or strings.

Syntax

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

Example

const arr = [1, 2, 3, 4, 5]; // Initiating an array

for (let value of arr) {
    console.log(value);
}

Output in console

1
2
3
4
5

Leave a Reply

Your email address will not be published. Required fields are marked *