JavaScript tutorials  /  Loops in JavaScript
Chapter 5 · JavaScript

Loops in JavaScript

A loop is a control flow structure in JavaScript that repeatedly executes a block of code as long as a specified condition remains true, allowing developers to perform repetitive tasks efficiently without writing the same code multiple times.

A loop lets your program repeat a set of instructions multiple times instead of writing them out one by one. You define a condition that controls how many times the code should repeat, and the loop keeps running the code block until that condition becomes false, or until a specific collection of items has been fully processed.

Think of a washing machine's spin cycle. It doesn't spin just once; it repeats the spinning motion a set number of times or until a timer runs out, then it stops automatically. Similarly, in a food delivery app, when displaying a list of restaurants near a user, JavaScript uses a loop to go through each restaurant object in an array and render its name, rating, and delivery time on the screen, one after another, without writing separate code for each individual restaurant. Another example is an attendance system that loops through a list of student names to mark each one as 'Present' or 'Absent'.

Loops are essential because many real-world programming tasks involve repeating an action multiple times, such as processing every item in an array, validating multiple form fields, generating repeated HTML elements, or retrying a failed network request a certain number of times. Without loops, developers would need to manually duplicate code for every repetition, which is inefficient, error-prone, and impossible when the number of repetitions is unknown in advance or depends on dynamic data, like the length of an array fetched from an API.

  • for Loop: A loop that repeats a block of code a specific number of times, controlled by three components: initialization, condition, and increment/decrement, all defined in a single line. It is ideal when the number of iterations is known in advance.
  • while Loop: A loop that repeats a block of code as long as a specified condition remains true, checking the condition before each iteration. It is useful when the number of iterations is not known beforehand and depends on a dynamic condition.
  • do-while Loop: Similar to a while loop, but it checks the condition after executing the code block, guaranteeing that the loop body runs at least once, even if the condition is false from the start.
  • for...in Loop: A loop specifically designed to iterate over the enumerable property names (keys) of an object, commonly used to loop through object properties rather than array elements.
  • for...of Loop: A loop introduced in ES6 that iterates over the values of an iterable object, such as arrays, strings, maps, and sets, providing a cleaner syntax than a traditional for loop when index access isn't needed.
// for loop for (let i = 0; i < 5; i++) { console.log(i); } // while loop let i = 0; while (i < 5) { console.log(i); i++; } // do-while loop let j = 0; do { console.log(j); j++; } while (j < 5); // for...of loop (arrays/iterables) for (const value of [10, 20, 30]) { console.log(value); } // for...in loop (object keys) for (const key in { a: 1, b: 2 }) { console.log(key); }
Suppose you are building a shopping cart feature where you need to calculate the total price of all items added by a user. The number of items in the cart can vary from user to user, so you cannot write separate lines of code to add each item's price manually. You need a way to go through every item in the cart array, regardless of how many there are, and accumulate their prices into a running total. Loops solve this by allowing you to iterate through the array once, applying the same price-adding logic to each item automatically.
Basic for Loop to Sum Array Elements
Demonstrates using a traditional for loop to iterate through an array of prices and calculate their total sum.
JavaScript
const prices = [250, 400, 150, 600]; let total = 0; for (let i = 0; i < prices.length; i++) { total += prices[i]; } console.log("Total price:", total);
Total price: 1400
The for loop initializes i to 0, checks the condition i < prices.length before each iteration, and increments i by 1 after each pass. On every iteration, the current price at index i is added to the total variable, resulting in the sum of all array elements.
while Loop for Unknown Number of Iterations
Demonstrates using a while loop to repeatedly halve a number until it becomes less than 1, showing a scenario where the number of iterations isn't known in advance.
JavaScript
let value = 100; let steps = 0; while (value >= 1) { value = value / 2; steps++; } console.log(`It took ${steps} steps to reduce value below 1`);
It took 7 steps to reduce value below 1
The while loop checks the condition 'value >= 1' before every iteration and keeps halving the value until it drops below 1. Since the exact number of iterations isn't known upfront, a while loop is more suitable here than a for loop.
do-while Loop Guaranteeing At Least One Execution
Demonstrates how a do-while loop runs its code block at least once, even when the initial condition is false.
JavaScript
let attempts = 5; do { console.log(`Attempt number: ${attempts}`); attempts++; } while (attempts < 5); console.log("Loop finished");
Attempt number: 5 Loop finished
Even though the condition 'attempts < 5' is false from the very start (since attempts is already 5), the do-while loop still executes the code block once before checking the condition, printing 'Attempt number: 5' exactly one time before exiting.
for...of vs for...in Loop Comparison
Demonstrates the key difference between for...of, which iterates over values, and for...in, which iterates over keys/indices, using both an array and an object.
JavaScript
const fruits = ["Apple", "Banana", "Mango"]; console.log("Using for...of (values):"); for (const fruit of fruits) { console.log(fruit); } console.log("Using for...in (indices):"); for (const index in fruits) { console.log(index); } const user = { name: "Amit", age: 28, city: "Delhi" }; console.log("Using for...in on object (keys):"); for (const key in user) { console.log(`${key}: ${user[key]}`); }
Using for...of (values): Apple Banana Mango Using for...in (indices): 0 1 2 Using for...in on object (keys): name: Amit age: 28 city: Delhi
for...of directly gives the actual values in the array (Apple, Banana, Mango), while for...in gives the array's indices as strings (0, 1, 2) since arrays are technically objects with numeric keys. When used on a plain object, for...in correctly iterates over its property keys, which is its intended use case.
  • Creating an Infinite Loop by Forgetting to Update the Condition Variable: Forgetting to increment or update the loop control variable inside a while or do-while loop causes the condition to never become false, resulting in an infinite loop that freezes the browser tab or crashes the program by consuming excessive memory and CPU.
  • Using for...in to Iterate Over Arrays: Using a for...in loop on an array iterates over the array's indices as strings (and potentially any additional enumerable properties added to the array or its prototype), which can lead to unexpected behavior. for...of or a traditional for loop should be used instead when iterating over array values.
  • Off-by-One Errors in Loop Conditions: Using the wrong comparison operator (like <= instead of <, or vice versa) in a for loop's condition can cause the loop to run one time too many or one time too few, commonly resulting in an 'undefined' value being accessed at an out-of-bounds array index or the last element being skipped.
  • Modifying the Array Being Iterated Over Inside the Loop: Adding or removing elements from an array while iterating over it with for, for...of, or forEach can cause elements to be skipped or processed twice, since the array's length and indices shift dynamically during iteration, leading to unpredictable behavior.
  • Using var Instead of let in for Loops with Closures: Declaring the loop counter with 'var' instead of 'let' inside a for loop that creates closures (like setTimeout callbacks) causes all closures to reference the same final value of the variable after the loop ends, since 'var' is function-scoped rather than block-scoped, leading to unexpected results like all callbacks logging the same last value instead of each iteration's value.
  • Use for...of for Arrays and Iterables When Index Isn't Needed: Prefer for...of over traditional for loops or for...in when iterating over array values or other iterables like strings, maps, and sets, since it provides cleaner, more readable syntax and directly accesses values instead of indices.
  • Reserve for...in Strictly for Object Property Iteration: Use for...in only when you specifically need to iterate over the enumerable keys of a plain object, and avoid using it on arrays to prevent unexpected behavior related to inherited or non-index properties.
  • Always Ensure the Loop's Terminating Condition Will Eventually Be Met: Before writing a while or do-while loop, verify that the loop control variable is being updated correctly inside the loop body so that the condition will eventually evaluate to false, preventing infinite loops that can freeze or crash the application.
  • Use let Instead of var for Loop Counters: Declare loop counters using 'let' instead of 'var' in for loops, especially when creating closures inside the loop, since 'let' is block-scoped and creates a new binding for each iteration, avoiding common closure-related bugs.
  • Consider Array Methods as Alternatives for Common Iteration Patterns: For common tasks like transforming, filtering, or reducing array data, consider using built-in array methods like map(), filter(), and reduce() instead of manual loops, as they often produce more concise, readable, and less error-prone code for these specific use cases.
What is the difference between a while loop and a do-while loop in JavaScript?
A while loop checks its condition before executing the loop body, meaning if the condition is false from the start, the loop body never executes at all. A do-while loop checks its condition after executing the loop body, guaranteeing that the code inside the loop runs at least once, even if the condition is false on the very first check.
What is the key difference between for...in and for...of loops in JavaScript?
The for...in loop iterates over the enumerable property names (keys) of an object, and when used on an array, it returns the indices as strings. The for...of loop iterates over the actual values of an iterable object, such as the elements of an array, characters of a string, or entries of a Map or Set. for...of is generally preferred for arrays and other iterables when you need the values directly, while for...in is intended for iterating over object properties.
What causes an infinite loop in JavaScript, and how can it be avoided?
An infinite loop occurs when the loop's terminating condition never becomes false, typically because the loop control variable is not being updated correctly, or the update logic never actually causes the condition to change from true to false. It can be avoided by carefully ensuring that every loop has a properly updating control variable, double-checking the loop's exit condition logic, and using tools like breakpoints or console logs to verify the loop behaves as expected during development.
Why does using 'var' instead of 'let' in a for loop cause issues with closures, such as in setTimeout callbacks?
'var' is function-scoped, meaning there is only a single shared binding of the loop variable across all iterations. When closures (like setTimeout callbacks) reference this variable, they all end up referencing the same final value after the loop completes, rather than the value at the time the closure was created. 'let' is block-scoped, so it creates a new binding for the variable on each iteration, allowing each closure to correctly capture and remember its own iteration's value.
What is the difference between using break and continue inside a loop?
The 'break' statement immediately terminates the entire loop, and execution jumps to the code immediately following the loop, regardless of whether all iterations have completed. The 'continue' statement skips only the current iteration of the loop, immediately proceeding to the next iteration's condition check, without executing any remaining code in the current iteration's block.
How would you iterate over both the keys and values of a plain JavaScript object, and what are the recommended approaches?
You can use a for...in loop combined with bracket notation (object[key]) to access both keys and their corresponding values. Alternatively, and often preferred in modern JavaScript, you can use Object.entries(object) combined with a for...of loop or array destructuring, like 'for (const [key, value] of Object.entries(obj))', which provides a cleaner and more explicit way to access both keys and values simultaneously without relying on for...in's potential pitfalls with inherited properties.
Write a JavaScript program using a for loop to print all even numbers between 1 and 20 (inclusive).
for (let i = 1; i <= 20; i++) { if (i % 2 === 0) { console.log(i); } }
Write a function 'sumUntilLimit' that uses a while loop to keep adding numbers starting from 1 (1, 2, 3, ...) until the running total exceeds a given limit, then returns the total and the last number added.
function sumUntilLimit(limit) { let total = 0; let number = 1; while (total <= limit) { total += number; number++; } return { total, lastNumberAdded: number - 1 }; } console.log(sumUntilLimit(50));
Write a program that uses for...of to iterate over an array of student objects (each with 'name' and 'marks' properties) and prints each student's name along with 'Pass' if marks are 40 or above, or 'Fail' otherwise. Use for...in separately to print all property names of the first student object.
const students = [ { name: "Neha", marks: 55 }, { name: "Raj", marks: 32 }, { name: "Priya", marks: 41 } ]; for (const student of students) { const result = student.marks >= 40 ? "Pass" : "Fail"; console.log(`${student.name}: ${result}`); } console.log("Properties of first student object:"); for (const key in students[0]) { console.log(key); }

Loops in JavaScript allow a block of code to be executed repeatedly based on a condition, avoiding the need to duplicate code for repetitive tasks. The main loop types are the for loop (best for a known number of iterations), the while loop (best for condition-based repetition), the do-while loop (guarantees at least one execution), the for...in loop (for iterating object keys), and the for...of loop (for iterating values of arrays and other iterables). Choosing the right loop type, avoiding infinite loops, and using let instead of var for loop counters are key practices for writing correct, maintainable looping logic.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.