| JavaScript-Conditionals | JavaScript: Break & Continue | |
JavaScript Loops (for, while, do…while) |
Loops are the backbone of repetition in JavaScript. Also in any programming language. They let you run a block of code multiple times until a condition is met. Let’s go through the three main loops: for, while, and do…while.
The for loop is used when you know how many times you want to run the code.
It has 3 parts: initialization, condition, and increment/decrement.
// Print numbers 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1 2 3 4 5
The while loop runs as long as the condition is true.
It’s useful when the number of iterations is not known in advance.
// Print numbers 1 to 5
let j = 1;
while (j <= 5) {
console.log(j);
j++;
}
// Output: 1 2 3 4 5
The do…while loop is similar to while,
but it always runs the code block at least once, even if the condition is false.
// Print numbers 1 to 5
let k = 1;
do {
console.log(k);
k++;
} while (k <= 5);
// Output: 1 2 3 4 5
// Calculate sum of numbers 1 to 5 using a for loop
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i;
}
console.log("Sum = " + sum); // Sum = 15
for when the number of iterations is known, while or do…while when it depends on a condition.let i = 0;
while(i < 5) {
console.log(i);
i++; // ensures termination
}
for(let index = 0; index < items.length; index++) { ... }
for(let i = 0; i < arr.length; i++) {
if(arr[i] === target) break;
}
for(let i = 0; i < arr.length; i++) {
if(arr[i] === null) continue;
console.log(arr[i]);
}
forEach, map, filter, reduce. | JavaScript-Conditionals | JavaScript: Break & Continue | |