Used when the number of iterations is known in advance.
Example:
for(let i = 0; i < 5; i++) {
console.log("Count:", i);
}
Problem:
Print all even numbers from 1 to 10.
Solution:
for(let i = 1; i <= 10; i++) {
if(i % 2 === 0) console.log(i);
}
Best when you don't know how many times you'll loop.
Example:
let i = 0;
while(i < 5) {
console.log("i is:", i);
i++;
}
Use Case:
Keep asking user input until a valid number is entered.
Similar to while loop, but executes at least once.
Example:
let count = 0;
do {
console.log("count:", count);
count++;
} while(count < 3);
Problem:
Print numbers until a randomly generated number is more than 0.7
let rand;
do {
rand = Math.random();
console.log(rand);
} while(rand <= 0.7);
Used to iterate over iterable values like arrays or strings.
Example:
const fruits = ["๐", "๐", "๐"];
for (const fruit of fruits) {
console.log(fruit);
}
Use Case:
Loop through characters in a password string to check if it includes digits.
Used to iterate over object keys.
Example:
const person = { name: "Alice", age: 25, city: "Paris" };
for (let key in person) {
console.log(key + ":", person[key]);
}
Use Case:
List all properties of a user object for display on a profile page.
Simplifies array iteration with a callback function.
Example:
const scores = [90, 85, 77];
scores.forEach((score, index) => {
console.log(`Score ${index + 1}:`, score);
});
Use Case:
Logging order items and their prices in an e-commerce app.
Returns a new array by transforming each element.
Example:
const prices = [100, 200, 300];
const withTax = prices.map(p => p * 1.18);
console.log(withTax);
Use Case:
Apply a transformation (like currency conversion or tax addition).