In JavaScript, loops are used to execute a block of code repeatedly until a specified condition is met. There are several types of loops available:
-
for Loop:
- Executes a block of code a specified number of times.
for (let i = 0; i < 5; i++) { console.log(i); }
-
while Loop:
- Executes a block of code while a specified condition is true.
let i = 0; while (i < 5) { console.log(i); i++; }
-
do...while Loop:
- Similar to a while loop but guarantees that the code inside the loop will run at least once before checking the condition.
let i = 0; do { console.log(i); i++; } while (i < 5);
-
for...in Loop:
- Iterates over the enumerable properties of an object.
const person = { name: 'Alice', age: 30 }; for (let key in person) { console.log(`${key}: ${person[key]}`); }
-
for...of Loop (ES6+):
- Iterates over iterable objects like arrays, strings, maps, sets, etc.
const numbers = [1, 2, 3, 4, 5]; for (let number of numbers) { console.log(number); }
-
forEach Method (Array):
- Executes a provided function once for each array element.
const colors = ['red', 'green', 'blue']; colors.forEach(function(color) { console.log(color); });
-
Map Method (Array):
- Creates a new array by performing an operation on each element of an existing array.
const numbers = [1, 2, 3]; const doubled = numbers.map(function(number) { return number * 2; }); console.log(doubled); // Output: [2, 4, 6]
These loops provide different ways to iterate through data structures, perform actions based on conditions, and manipulate arrays or objects in JavaScript. The choice of loop depends on the specific requirement and the data structure being iterated over.