In JavaScript, loops are control structures that allow you to repeatedly execute a block of code as long as a certain condition is met. There are two commonly used types of loops in JavaScript: for
loops and while
loops.
For Loop
A for
loop is typically used when you know beforehand how many times you want to execute the loop.
A for
loop is used when you know how many times you want to repeat a task or iterate through a sequence of items. Here’s a real-life example:
Imagine you’re developing a feature for Amazon’s shopping cart. You have an array of items a customer wants to purchase, and you need to calculate the total price of their order.
const items = [10, 20, 30, 40, 50];
let totalPrice = 0;
for (let i = 0; i < items.length; i++) {
totalPrice += items[i];
}
console.log(`Total price: $${totalPrice}`);
JavaScriptIn this code, the for
loop iterates through the items array, and with each iteration, it adds the item’s price to the totalPrice
. This loop repeats until all items are processed, providing the total cost of the order.
While Loop
A while
loop is used when you don’t know in advance how many times you’ll need to execute the loop but have a condition that, when met, should end the loop.
A while
loop is used when you don’t know in advance how many times you need to repeat a task but have a condition that determines when to stop. Let’s look at a real-life example from login page.
Here’s an example of a while loop in JavaScript that simulates a basic Facebook-like functionality. We’ll create a simplified version of a user login system:
// Sample user data
const users = [
{ username: "user1", password: "password1" },
{ username: "user2", password: "password2" },
{ username: "user3", password: "password3" },
];
// Simulate a login system using a while loop
let loggedIn = false;
let attempts = 3;
while (attempts > 0) {
const username = prompt("Enter your username:");
const password = prompt("Enter your password:");
// Check if the entered credentials match any user in the array
const user = users.find((u) => u.username === username && u.password === password);
if (user) {
loggedIn = true;
console.log("Login successful!");
break; // Exit the loop on successful login
} else {
attempts--;
console.log(`Login failed. ${attempts} attempts remaining.`);
}
}
if (!loggedIn) {
console.log("Login attempts exhausted. Please try again later.");
}
JavaScriptIn this example, we have an array of user data and a while loop that allows the user to attempt to log in with their username and password. The loop continues until the user either successfully logs in or exhausts their login attempts. If the user enters the correct credentials, the loop exits and displays “Login successful.” If the user fails to log in within three attempts, it displays “Login attempts exhausted.”
Both for
and while
loops are essential tools for automating repetitive tasks in JavaScript, making them useful for scenarios ranging from e-commerce platforms like Amazon and Flipkart to various other real-life applications.
Conclusion
Both for
and while
loops play crucial roles in JavaScript for iterating over data and automating tasks. Choosing between them depends on whether you know the number of iterations beforehand (for
loop) or if you’re operating based on a condition (while
loop). Understanding these loops enhances your ability to write efficient, effective code, applicable across various programming scenarios from web development to server-side applications.
Frequently Asked Questions
Ans: Loops are control structures in JavaScript that repeat a block of code as long as a specified condition is true. They are used to automate repetitive tasks.
Q2. What is a
for
loop and when should it be used? Ans: A for
loop is used when you know the exact number of times you need to repeat an action. It is particularly useful for iterating over arrays or executing a block of code a specific number of times.
Q3. How does a
while
loop work? Ans: A while
loop continues to execute a block of code as long as its condition remains true. It’s ideal when you don’t know in advance how many iterations are needed but have a condition to end the loop.
Q4. What’s the difference between
for
and while
loops? Ans: The main difference is in their usage: for
loops are used when the number of iterations is known, while while
loops are preferred when the number of iterations is unknown but defined by a condition.
Q5. Can you provide an example of a
for
loop? Ans: Yes, an example of a for
loop to calculate the total price of items in a shopping cart:const items = [10, 20, 30, 40, 50];
let totalPrice = 0;
for (let i = 0; i < items.length; i++) {
totalPrice += items[i]; }
console.log(`Total price: $${totalPrice}`);