JavaScript Essentials: Control Flow - Loops
Loops are fundamental building blocks in programming, allowing you to execute a block of code repeatedly. JavaScript provides several types of loops to handle different scenarios. This document covers the most common loop types: for, while, and do...while.
1. for Loop
The for loop is ideal when you know in advance how many times you want to execute a block of code.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed repeatedly
}
- initialization: Executed once at the beginning of the loop. Typically used to declare and initialize a counter variable.
- condition: Evaluated before each iteration. If the condition is true, the loop continues. If false, the loop terminates.
- increment/decrement: Executed after each iteration. Usually used to update the counter variable.
Example:
// Print numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output:
// 1
// 2
// 3
// 4
// 5
Explanation:
let i = 1;: Initializes a variableito 1.i <= 5;: Checks ifiis less than or equal to 5.console.log(i);: Prints the current value ofi.i++;: Incrementsiby 1.- Steps 2-4 repeat until
iis greater than 5.
for...in Loop:
Used to iterate over the enumerable properties of an object. The order of iteration is not guaranteed.
const myObject = { a: 1, b: 2, c: 3 };
for (let key in myObject) {
console.log(key + ": " + myObject[key]);
}
// Output:
// a: 1
// b: 2
// c: 3
for...of Loop:
Used to iterate over the values of iterable objects (e.g., arrays, strings, Maps, Sets).
const myArray = [10, 20, 30];
for (let value of myArray) {
console.log(value);
}
// Output:
// 10
// 20
// 30
2. while Loop
The while loop executes a block of code as long as a specified condition is true. It's useful when you don't know in advance how many times the loop needs to run.
Syntax:
while (condition) {
// Code to be executed repeatedly
}
Example:
// Count down from 5 to 1
let count = 5;
while (count > 0) {
console.log(count);
count--;
}
// Output:
// 5
// 4
// 3
// 2
// 1
Explanation:
let count = 5;: Initializes a variablecountto 5.count > 0;: Checks ifcountis greater than 0.console.log(count);: Prints the current value ofcount.count--;: Decrementscountby 1.- Steps 2-4 repeat until
countis not greater than 0.
3. do...while Loop
The do...while loop is similar to the while loop, but it guarantees that the code block will be executed at least once, even if the condition is initially false.
Syntax:
do {
// Code to be executed repeatedly
} while (condition);
Example:
// Prompt the user for input until they enter a valid number
let input;
do {
input = prompt("Enter a number greater than 10:");
} while (isNaN(input) || input <= 10);
console.log("You entered: " + input);
Explanation:
- The code inside the
doblock is executed once. isNaN(input) || input <= 10;: Checks if the input is not a number (isNaN) or if it's less than or equal to 10.- If the condition is true, the loop repeats. If false, the loop terminates.
Loop Control Statements
JavaScript provides statements to control the execution of loops:
break: Immediately terminates the loop and transfers control to the statement following the loop.
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit the loop when i is 5
}
console.log(i);
}
// Output:
// 0
// 1
// 2
// 3
// 4
continue: Skips the current iteration of the loop and proceeds to the next iteration.
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i);
}
// Output:
// 1
// 3
// 5
// 7
// 9
Choosing the Right Loop
forloop: Use when you know the number of iterations in advance.whileloop: Use when you need to repeat a block of code as long as a condition is true, and you don't know the number of iterations beforehand.do...whileloop: Use when you need to execute a block of code at least once, regardless of the condition.
Understanding and effectively using loops is crucial for writing efficient and dynamic JavaScript code. Practice with these different loop types and control statements to become proficient in JavaScript programming.