Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created September 30, 2024 17:29
Show Gist options
  • Save decagondev/f315247ffa1a166c00c84ea28660d334 to your computer and use it in GitHub Desktop.
Save decagondev/f315247ffa1a166c00c84ea28660d334 to your computer and use it in GitHub Desktop.

Types of Loops in JavaScript

  1. For Loop
  2. While Loop
  3. Do While Loop
  4. ForEach Loop
  5. Map Method

1. For Loop

The for loop is used to execute a block of code a specified number of times.

Syntax:

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

Example:

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

2. While Loop

The while loop executes the code block as long as the specified condition is true.

Syntax:

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

Example:

let i = 0;
while (i < 5) {
    console.log("Iteration:", i);
    i++;
}

3. Do While Loop

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

Syntax:

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

Example:

let i = 0;
do {
    console.log("Iteration:", i);
    i++;
} while (i < 5);

4. ForEach Loop

The forEach loop is array-specific and is used to execute a function once for each array element.

Syntax:

array.forEach(function(currentValue, index, arr), thisValue)

Example:

let arr = [1, 2, 3, 4, 5];
arr.forEach((value, index) => {
    console.log("Value at index", index, "is", value);
});

5. Map Method

The map method creates a new array populated with the results of calling a provided function on every element in the calling array.

Syntax:

let newArray = array.map(function(currentValue, index, arr), thisValue)

Example:

let arr = [1, 2, 3, 4, 5];
let squaredArr = arr.map(value => value * value);
console.log(squaredArr); // [1, 4, 9, 16, 25]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment