JavaScript Loops

JavaScript Loops (for, while, do-while, for…of, for…in)

A complete beginner-friendly guide to JavaScript loops with clear explanations, practical examples, and real-world use cases.

In JavaScript, a loop is a control structure that allows you to execute a block of code repeatedly as long as a specified condition remains true. Loops are essential for performing repetitive tasks efficiently, such as processing data, iterating through arrays, or handling user input.

Instead of writing the same code multiple times, loops enable developers to write cleaner, more maintainable, and more readable programs. JavaScript offers several types of loops, each designed for specific scenarios and data structures.

Types of Loops in JavaScript

JavaScript provides multiple looping mechanisms to handle different iteration needs. Choosing the right loop improves performance and code clarity.

  • for loop – used when the number of iterations is known
  • while loop – runs while a condition remains true
  • do-while loop – executes at least once before checking the condition
  • for…of loop – iterates over iterable objects like arrays and strings
  • for…in loop – iterates over object properties

Example 1: JavaScript for Loop

The for loop is one of the most commonly used loops in JavaScript. It is ideal when the number of iterations is known beforehand. A for loop consists of three parts: initialization, condition, and increment/decrement.

JavaScript Example

for (let i = 1; i <= 5; i++) {
    console.log(i);
}
                
Try it Yourself »

JavaScript for Loop

The JavaScript for loop is a control flow statement that allows you to execute a block of code repeatedly as long as a specified condition evaluates to true. It is most commonly used when the number of iterations is known before the loop starts.

A for loop combines three important expressions into a single line: initialization, condition, and increment or decrement. This structure makes the loop compact, readable, and easy to control.

Syntax

for (initialization; condition; increment/decrement) {
    // code to be executed
}
        

Example

JavaScript Example

for (let i = 1; i <= 5; i++) {
    console.log("Iteration number: " + i);
}
        
Try it Yourself »

Explanation

  • The loop starts by initializing the counter variable: let i = 1
  • Before each iteration, the condition i <= 5 is evaluated; the loop continues as long as it remains true
  • After each iteration, the counter is increased using i++
  • During every loop cycle, the current value of i is printed to the console

JavaScript while Loop

In JavaScript, the while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to true. The condition is checked before each iteration.

The while loop is especially useful when the number of iterations is not known in advance and depends on dynamic conditions. To prevent an infinite loop, the condition must eventually become false inside the loop.

Syntax

while (condition) {
    // code block to be executed
}
        

Example

JavaScript Example

let count = 1;

while (count <= 5) {
    console.log("Current count:", count);
    count++;
}
        
Try it Yourself »

Explanation

In this example, the while loop continues to run as long as the condition count <= 5 remains true. The variable count is updated during each iteration, ensuring that the loop eventually stops.

  • Initializes the loop control variable: let count = 1
  • Evaluates the condition before every iteration: count <= 5
  • Executes the loop body and increments the value using count++
  • Stops execution once the condition becomes false

JavaScript do-while Loop

The do-while loop in JavaScript is a control flow statement that executes a block of code at least once before evaluating the condition. After the first execution, the loop continues to run as long as the specified condition evaluates to true.

Unlike the while loop, where the condition is checked first, a do-while loop checks the condition after the loop body runs. This makes it useful in situations where the code must execute at least one time, such as displaying menus or prompting user input.

Syntax

do {
    // code to execute
} while (condition);
        

Example

JavaScript Example

let number = 1;

do {
    console.log("Current number:", number);
    number++;
} while (number <= 5);
        
Try it Yourself »

Explanation

In this example, the do-while loop prints the value of number to the console. The loop runs at least once because the condition is evaluated after the loop body executes.

  • Initializes the variable: let number = 1
  • Executes the loop body and prints the current value
  • Increments the value using number++
  • Checks the condition number <= 5 after execution
  • Stops when the condition becomes false

JavaScript for…of Loop

The for…of loop in JavaScript is used to iterate directly over the values of iterable objects such as arrays, strings, maps, and sets. It provides a clean and readable way to access each value without working with indexes.

This loop is especially useful when you only need to work with the values of a collection and do not require the index or key.

Syntax

for (variable of iterable) {
    // code to execute
}
        

Example

JavaScript Example

const colors = ['Red', 'Green', 'Blue'];

for (const color of colors) {
    console.log(color);
}
        
Try it Yourself »

Explanation

  • Declares an array of color values: ['Red', 'Green', 'Blue']
  • The for…of loop accesses each value in the array one by one
  • The variable color stores the current value during each iteration
  • Logs each color value to the console

JavaScript for…in Loop

The for…in loop in JavaScript is used to iterate over the enumerable properties (keys) of an object. It loops through each property name and is commonly used when working with object data.

The for…in loop should generally be used for objects, not arrays, because it iterates over property names rather than values.

Syntax

for (key in object) {
    // code to execute
}
        

Example: Iterating Over Object Keys

JavaScript Example

const userProfile = {
    name: "John",
    age: 30,
    country: "USA"
};

for (const property in userProfile) {
    console.log(property);
}
        
Try it Yourself »

Output (Keys)

name
age
country

Example: Accessing Object Values

const userProfile = {
    name: "John",
    age: 30,
    country: "USA"
};

for (const property in userProfile) {
    console.log(userProfile[property]);
}
        
Try it Yourself »

Explanation

  • The object userProfile contains key-value pairs
  • The for…in loop iterates over each property name (key)
  • Object values are accessed using bracket notation: object[key]
  • This loop is ideal for processing object properties

How to Choose the Right Loop?

  • Use for loop when the number of iterations is known in advance.
  • Use while loop when the loop depends on a dynamic condition.
  • Use do-while loop when the code must run at least once.
  • Use for…in loop to iterate over object properties (keys).
  • Use for…of loop to iterate over iterable values like arrays or strings.

Frequently Asked Questions (FAQs) about JavaScript Loops

❓ What are loops in JavaScript?

JavaScript loops are control structures that allow you to execute a block of code repeatedly as long as a specified condition remains true. They are commonly used to iterate over arrays, objects, strings, and perform repetitive tasks efficiently.

❓ How many types of loops are there in JavaScript?

JavaScript provides several types of loops:

  • for loop
  • while loop
  • do-while loop
  • for…of loop
  • for…in loop

Each loop serves a different purpose depending on the data structure and use case.

❓ Which loop is best in JavaScript?

There is no single “best” loop in JavaScript. The best loop depends on your requirement:

  • Use for loop when the number of iterations is known
  • Use while loop for dynamic conditions
  • Use do-while loop when the code must run at least once
  • Use for…of for array or iterable values
  • Use for…in for object properties

❓ What is the difference between for…of and for…in loops?

for…of iterates over values of iterable objects like arrays and strings.
for…in iterates over keys (properties) of objects.
👉 Use for…of for arrays and for…in for objects.

❓ Can JavaScript loops cause infinite loops?

Yes. An infinite loop occurs when the loop condition never becomes false. This can freeze the browser or crash the program. Always ensure the loop condition is updated properly inside the loop.

while (true) {
  console.log("Infinite loop");
}
        

❓ When should I use a while loop instead of a for loop?

Use a while loop when:

  • The number of iterations is unknown
  • The loop depends on user input or dynamic conditions

Use a for loop when the iteration count is predictable.

❓ Are JavaScript loops slow?

JavaScript loops are generally fast and efficient. Performance issues usually occur due to:

  • Infinite loops
  • Heavy computations inside loops
  • Poor logic or unnecessary nesting

Modern JavaScript engines optimize loops very well.

❓ Can I stop a loop in JavaScript?

Yes. You can stop a loop using the break statement or skip an iteration using continue.

for (let i = 1; i <= 5; i++) {
  if (i === 3) break;
  console.log(i);
}