Real-Life Example of a Loop
Imagine you're asked to print all numbers from 1 to 10. You could write 10 print statements, but that's not efficient. Instead, you can use a loop to iterate from 1 to 10 and print each number. This is how loops help automate repetitive tasks.
In a similar way, if you wanted to sum all elements in an array, you'd use a loop to go through each element. This same concept exists in most languages, including C and Java.
What is a Loop?
A loop in programming is a control structure that allows you to execute a block of code multiple times. Instead of writing repetitive code, you can use loops to repeat actions a specified number of times or until a certain condition is met.
In JavaScript, like in C or Java, a loop can be used to iterate over arrays, perform calculations, and automate repetitive tasks. Loops are fundamental in programming for handling tasks like traversing through data, managing timers, or repeatedly performing calculations.
Types of Loops in JavaScript
JavaScript provides several types of loops, just like C and Java. The most commonly used are:
- for: Used when the number of iterations is known ahead of time. It's similar to C/Java's
forloop. - while: Used when you want to repeat code until a specific condition is met. Similar to C/Java's
whileloop. - do...while: Executes the loop at least once, regardless of the condition, and then checks if the condition is true. This is similar to C/Java's
do-whileloop. - for...in: Used to iterate over the properties of an object.
- for...of: Used to iterate over iterable objects like arrays, maps, and sets.
Note : We will discuss for...in and for...of later. So don't worry. Don't want to confuse you.
Looping with `for` and `while`
Here's how you can use the for and while loops in JavaScript:
// Using for loop
for (let i = 0; i < 5; i++) {
console.log(i); // Output: 0 1 2 3 4
}
// Using while loop
let i = 0;
while (i < 5) {
console.log(i); // Output: 0 1 2 3 4
i++;
}Break and Continue Statements
In both JavaScript and C/Java, you can control the flow of loops with the break and continue statements:
- break: Exits the loop entirely, regardless of the condition. If used inside a nested loop, it only exits the innermost loop.
- continue: Skips the current iteration and moves to the next iteration of the loop. It does not exit the loop.
// Example of break and continue
for (let i = 0; i < 5; i++) {
if (i === 3) {
break; // Exits the loop when i is 3
}
console.log(i); // Output: 0 1 2
}
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // Skips the iteration when i is 2
}
console.log(i); // Output: 0 1 3 4
}Looping with `do...while`
Here's how you can use the do...while loop in JavaScript:
// Using do...while loop
let i = 0;
do {
console.log(i); // Output: 0 1 2 3 4
i++;
} while (i < 5);In this case, the loop starts with i = 0 and increments i after each iteration. The output will be: 0 1 2 3 4, printed to the console.
Nested Loops
A nested loop is a loop inside another loop. It is used when you need to perform repetitive tasks within another set of tasks, like iterating over a matrix or a table in a 2D array.
In JavaScript, just like in C/Java, you can have loops inside loops:
// Example of a nested loop
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 2; j++) {
console.log("i",i,"j",j); // Output: i: 0, j: 0 -> i: 0, j: 1 -> i: 1, j: 0 -> i: 1, j: 1 -> i: 2, j: 0 -> i: 2, j: 1
}
}Common Mistakes with Loops
Here are some common mistakes to avoid when working with loops in JavaScript (and other languages like C/Java):
- Infinite loops: If the loop's condition never becomes false, it results in an infinite loop. Always ensure that the loop has a valid exit condition.
- Off-by-one errors: This happens when the loop iterates one time too many or too few. Pay attention to the loop boundaries.
- Unintended skipping or exiting: Misplacing the
breakorcontinuestatements can cause unexpected behavior in your loop.
// Common mistakes in loops
// Infinite loop example (make sure you have a valid exit condition)
let i = 0;
while (i >= 0) {
console.log(i);
i++; // Add a proper condition to avoid infinite loop
}
// Off-by-one error
for (let i = 0; i <= 5; i++) {
console.log(i); // Output: 0 1 2 3 4 5 (wrong condition: should be i < 5)
}