- For Loop
- While Loop
- Do While Loop
- ForEach Loop
- Map Method
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);
}
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++;
}
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);
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);
});
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]