Apply Now Apply Now Apply Now
header_logo
Post thumbnail
JAVASCRIPT

Loops in JavaScript (2026): A Beginner’s Guide to Writing Cleaner Code

By Jebasta

Ever needed to print or process the same kind of value seven, seventeen, or seven thousand times, and dreaded typing it out by hand? That’s exactly the problem loops in JavaScript exist to solve.

Loops in JavaScript are structures that let you run the same block of code again and again, without having to type it out manually every single time. Instead of writing seven console.log() statements to print seven numbers, a single loop handles the repetition for you in just a few lines.

Whether you’re processing arrays, checking conditions, or just automating a repetitive task, picking the right loop makes your code cleaner and easier to follow. This guide breaks down every loop type in JavaScript, when to use each one, and how they actually work under the hood.

Table of contents


  1. TL;DR Summary
  2. Introduction to Loops in JavaScript
    • 1) The for Loop
    • 2) The do...while Loop
    • 3) The while Loop
    • 4) The Labeled Statement
    • 5) The break Statement
    • 6) The continue Statement
    • 7) The for...in Loop
    • 8) The for...of Loop
  3. Loops in JavaScript: Quick Comparison Table
  4. Loops vs Array Methods: forEach, map, and filter
  5. Best Practices for Using Loops
  6. Common Mistakes to Avoid
  7. Best JavaScript Courses in India 2026: Learn Loops and Core Concepts the Right Way
  8. Loops in JavaScript: Common Interview Questions
    • Q1. What does this print, and why?
    • Q2. How many times does this loop run?
    • Q3. What does continue with a label actually skip?
  9. Conclusion
  10. FAQs
    • What are the main four types of loops?
    • What are loops and arrays?
    • What is the most commonly used loop in JavaScript?
    • Which loop is faster in JavaScript?
    • Why use loops in JavaScript?

TL;DR Summary

  • What it is: loops in JavaScript are structures that let you repeat a block of code without writing it out again and again, saving time and keeping your code clean
  • Most commonly used: the for loop is the most popular of all the loops in JavaScript, since it packs initialization, condition, and increment into one line
  • Guaranteed to run once: do…while checks its condition after running, unlike most other loops in JavaScript that check first
  • For objects vs arrays: for…in loops through object properties, for…of loops through array or iterable values
  • Extra control: break exits a loop early, continue skips just the current iteration, both work across almost every one of these loops in JavaScript

Introduction to Loops in JavaScript

Introduction to Loops in JavaScript

Loops in JavaScript are control structures that allow us to repeatedly execute a block of code until a certain condition is met.

They are used when we want to perform an operation multiple times without having to write the same code over and over again. In JavaScript, there are several types of loops, each with its own syntax and use cases.

1) The for Loop

The for loop is one of the most commonly used loops in JavaScript. It allows us to execute a block of code a specified number of times. The syntax of the for loop is as follows:

for (initialization; condition; increment) {
  // code to be executed
}
  • The initialization step is executed only once before the loop starts. It is where we declare and initialize any variables used in the loop.
  • The condition is evaluated before each iteration, and if it evaluates to true, the loop continues.
  • The increment step is executed after each iteration, and is typically used to update the loop control variable.

Let’s see an example to illustrate the usage of the for loop:

for (let i = 1; i < 8; i++) {
  console.log(i);
}

In this example, the loop will iterate seven times, printing the values from 1 to 7 to the console.

Must Read: Master JavaScript Frontend Roadmap: From Novice to Expert

Ready to turn your knowledge of loops in JavaScript into a full career in web development?

HCL GUVI’s Software and AI Engineer Programme takes you from core JavaScript fundamentals to full-stack, backend, and AI-powered development, with hands-on projects, mentorship, mock interviews, and IITM-Pravartak certification.

2) The do…while Loop

The do…while loop is similar to the while loop, but with one key difference: the condition is evaluated after the code block has been executed.

This means that the code block will always execute at least once, regardless of the condition. The syntax of the do…while loop is as follows:

do {
  // code to be executed
} while (condition);

Let’s look at an example to understand how the do…while loop works:

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 10);

In this example, the code block executes once, printing the value of i to the console. Then the condition i < 10 is checked.

If it evaluates to true, the loop continues, and the code block runs again. This repeats until the condition becomes false, printing 0 through 9. It is one of the most versatile loops in JavaScript.

3) The while Loop

Among loops in JavaScript, the while loop is used to execute a block of code as long as a specified condition is true. It is similar to the do…while loop, but the condition is evaluated before the code block is executed.

The syntax of the while loop is as follows:

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

Let’s see an example to understand how the while loop works:

let i = 0;
while (i < 17) {
  console.log(i);
  i++;
}

In this example, the code block executes as long as the condition i < 17 is true, printing the values 0 through 16, 17 numbers in total. It is one of the most used loops in JavaScript.

Also Read: JavaScript Tools Every Developer Should Know

Before we move to the next section, make sure that you are strong in the full-stack development basics. If not, consider enrolling for a professionally certified online full-stack web development course by a recognized institution that can also offer you an industry-grade certificate that boosts your resume.

4) The Labeled Statement

Among loops in JavaScript, labels let you identify a loop or a block of code. Labels are often used with the break and continue statements to control the flow of the program. The syntax of a labeled statement is as follows:

label: statement

Let’s look at an example of using labels with the for loop and the break statement:

outerLoop: for (let i = 0; i < 9; i++) {
  innerLoop: for (let j = 0; j < 9; j++) {
    if (i === 1 && j === 1) {
      break outerLoop;
    }
    console.log(`i = ${i}, j = ${j}`);
  }
}

In this example, we have an outer loop labeled as outerLoop and an inner loop labeled as innerLoop.

When the condition i === 1 && j === 1 is met, the break statement is executed, causing the program to break out of the outer loop entirely, not just the inner one. This allows us to selectively break out of multiple nested loops.

5) The break Statement

The break statement is used to exit a loop or switch statement prematurely. When the break statement is encountered, the program flow immediately moves to the next statement outside of the loop or switch.

This is one of the most useful control tools among loops in JavaScript when we want to terminate a loop early based on a certain condition. Let’s see an example to understand how the break statement works:

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

In this example, the loop prints the values 0 through 4, five values in total. When i becomes 5, the break statement is executed, and the loop is terminated before it ever prints 5.

Develop your first project with us: 10 Best HTML and CSS Project Ideas for Beginners

6) The continue Statement

The continue statement is used to skip the current iteration of a loop and move on to the next iteration. Unlike the break statement, which terminates the loop, the continue statement only affects the current iteration.

This is another useful control tool among loops in JavaScript when we want to skip certain iterations based on a condition. Let’s look at an example to understand how the continue statement works:

for (let i = 0; i < 10; i++) {
  if (i === 9) {
    continue;
  }
  console.log(i);
}

In this example, the loop still runs its full 10 iterations (i = 0 through 9), but when i equals 9, the continue statement skips the console.log for that one iteration. As a result, the values 0 through 8 are printed, nine values total, and 9 never appears in the output.

7) The for…in Loop

Among loops in JavaScript, the for…in statement is used to iterate over the properties of an object. It allows us to access each property of an object and perform a specific action. The syntax of the for…in loop is as follows:

for (variable in object) {
  // code to be executed
}

Let’s see an example to understand how the for…in loop works:

const person = {
  name: "HCLGUVI",
  age: 10,
  city: "Chennai, Tamil Nadu"
};

for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}

In this example, the loop iterates over each property of the person object and prints the key-value pairs to the console. The output will be:

name: HCLGUVI
age: 10
city: Chennai, Tamil Nadu

Must Read: 4 Key Differences Between == and === Operators in JavaScript

8) The for…of Loop

Among loops in JavaScript, the for…of statement is used to iterate over iterable objects, such as arrays, strings, and other iterable built-in objects. It provides a simpler and more concise syntax compared to the for loop or the for…in loop.

The syntax of the for…of loop is as follows:

for (variable of iterable) {
  // code to be executed
}

Let’s look at an example to understand how the for…of loop works:

const languages = ["javascript", "python", "html"];

for (let lang of languages) {
  console.log(lang);
}

In this example, the loop iterates over each element in the languages array and prints the value to the console. The output will be:

javascript
python
html

Loops in JavaScript: Quick Comparison Table

The table below covers all the loops in JavaScript discussed in this guide, comparing how each one works and when to use it:

Loop TypeBest Used ForExecutes At Least OnceKey Characteristic
forRunning code a fixed, known number of timesNoCombines initialization, condition, and increment in one line
whileRepeating code while a condition stays true, when iteration count is unknownNoChecks the condition before running the code block
do…whileCases where the code must run at least once before checking the conditionYesChecks the condition after running the code block
for…inIterating over the properties (keys) of an objectNoNot ideal for arrays since it iterates over keys, not values
for…ofIterating over values in arrays, strings, and other iterablesNoCleaner syntax than for…in when values (not keys) are needed
Labeled StatementControlling flow in nested loopsNoUsed alongside break/continue to target a specific outer loop
breakExiting a loop early once a condition is metN/A (not a loop itself)Terminates the loop completely
continueSkipping the current iteration without ending the loopN/A (not a loop itself)Moves to the next iteration, skipping remaining code in that cycle
GUVI Ad

Loops vs Array Methods: forEach, map, and filter

Modern JavaScript gives you array methods as an alternative to traditional loops in JavaScript, and it’s worth knowing when each one actually makes sense.

ApproachCan Use break/continue?Returns a New Array?Best For
for / while / do…whileYesNoFull control, early exit, complex conditions
forEach()NoNoSimple iteration with no need to exit early
map()NoYesTransforming every element into a new array
filter()NoYesSelecting a subset of elements that match a condition
const numbers = [1, 2, 3, 4, 5];

// Traditional loop
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i] * 2);
}

// Array method equivalent
numbers.forEach(num => console.log(num * 2));

// map() when you need the transformed values back
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

When to reach for a traditional loop instead: if you need to break out early, skip iterations with continue, or loop over something that isn’t an array (like object properties), stick with for, while, or for…in.

Array methods like forEach, map, and filter don’t support break or continue at all.

Best Practices for Using Loops

When using loops in JavaScript, it’s important to follow best practices to ensure clean and efficient code. Here are some tips for using loops effectively:

  1. Use meaningful variable names: Choose variable names that accurately describe the purpose of the loop control variable. This makes the code more readable and understandable.
  2. Initialize variables outside the loop: If possible, initialize loop control variables outside the loop to avoid unnecessary reinitialization.
  3. Use the most appropriate loop for the task: Choose the loop that best fits your code’s requirements. Use a for loop when you know the number of iterations in advance, and a while loop when the number of iterations is unknown.
  4. Avoid infinite loops: Make sure your loops have a proper exit condition to prevent them from running indefinitely. Infinite loops can cause your program to crash or become unresponsive.
  5. Minimize code inside loops: Try to keep the code inside loops as concise as possible. Move any complex calculations or resource-intensive operations outside the loop if they don’t need to be repeated.
  6. Use break and continue judiciously: While break and continue statements can be useful, excessive use can make the code harder to understand and maintain. Use them sparingly and only when necessary.

Also Read: 30 Best JavaScript Project Ideas For You [3 Bonus Portfolio Projects]

Common Mistakes to Avoid

When working with loops in JavaScript, it’s easy to make mistakes that can lead to bugs or inefficient code. Here are some common mistakes to avoid:

  1. Forgetting to update the loop control variable: Make sure to update the loop control variable inside the loop to avoid infinite loops or incorrect results.
  2. Using the wrong loop type: Choose the appropriate loop type for the task at hand. Using the wrong loop type can lead to unnecessary complexity or inefficiency.
  3. Modifying the iterable object inside a for…of loop: If you modify the iterable object inside a for…of loop, it can cause unexpected behavior or errors. Consider creating a copy of the iterable object if you need to modify it.
  4. Not using curly braces for single-line blocks: While it’s possible to omit curly braces for single-line blocks in loops, it can lead to ambiguity and make the code harder to read. Always use curly braces, even for single-line blocks.
  5. Not initializing loop control variables: Always initialize loop control variables before using them in a loop. Failure to do so can result in undefined behavior or errors.

Must Read: 7 Best Reasons to Learn JavaScript | 1 Bonus Point

Best JavaScript Courses in India 2026: Learn Loops and Core Concepts the Right Way

If you’re looking to go beyond just loops in JavaScript and build a career in web development, here are some of the top courses available in India in 2026, ranging from free self-paced options to mentor-led programs with placement support.

Course NameOffered ByJS CoverageLink
Software and AI Engineer ProgrammeHCL GUVIPart of a full MERN stack curriculum (JS is the core scripting language across it)Course Page
The Complete JavaScript Course 2026Jonas Schmedtmann (Udemy)Dedicated, JS-only course from fundamentals to advancedCourse Page
JavaScript Algorithms and Data StructuresfreeCodeCampDedicated, JS-only certificationCourse Page
IBM Full-Stack JavaScript Developer Professional CertificateIBM (Coursera)Part of a full-stack curriculum (JS, Node.js, React, Express)Course Page
Introduction to JavaScript ISaylor Academy (via Skill India portal)Dedicated, JS-only introductory courseCourse Page
Meta Front-End Developer Professional CertificateMeta (Coursera)Part of a front-end curriculum (HTML, CSS, JS, React)Course Page
GUVI Ad

Loops in JavaScript: Common Interview Questions

These trip up even experienced developers, since they test how well you actually understand loop mechanics, not just syntax.

Q1. What does this print, and why?

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log("var:", i), 0);
}
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log("let:", j), 0);
}

Answer: the var version prints 3, 3, 3, while the let version prints 0, 1, 2. This is because var is function-scoped, so all three callbacks share the same i, which has finished looping (reaching 3) by the time they run. let is block-scoped, so each iteration gets its own separate j.

Q2. How many times does this loop run?

let count = 0;
for (let i = 10; i > 0; i -= 2) {
  count++;
}

Answer: 5 times. Starting at 10 and decreasing by 2 each time, i takes the values 10, 8, 6, 4, 2, all greater than 0, and then stops once i reaches 0.

Q3. What does continue with a label actually skip?

let result = [];
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) continue outer;
    result.push([i, j]);
  }
}

Answer: [[0,0], [1,0], [2,0]]. A labeled continue jumps straight to the next iteration of the labeled (outer) loop, not just the inner one, so as soon as j hits 1, the inner loop is abandoned entirely and i moves forward.

Conclusion

Loops in JavaScript are a fundamental tool in the language, allowing us to execute a block of code repeatedly.

In this comprehensive guide, we have explored the different types of loops in JavaScript, including the for, do…while, while, for…in, and for…of loops. We have also discussed best practices for using loops and common mistakes to avoid.

By mastering all the loops in JavaScript and the art of looping, you can write more efficient and powerful JavaScript code.

Must Explore: Variables and Data Types in JavaScript: A Complete Guide

FAQs

1. What are the main four types of loops?

The four main loops in JavaScript are for, while, do...while, and for...in/for...of. for runs a block a set number of times, while keeps running as long as a condition is true, do...while runs at least once before checking the condition, and for...in/for...of are used to loop through object properties or array/iterable values.

2. What are loops and arrays?

Loops are used to repeat a block of code multiple times without writing it out manually. Arrays are data structures that store ordered collections of values. The two are often used together — loops like for or for...of let you go through each element in an array and work with its values one by one.

3. What is the most commonly used loop in JavaScript?

The for loop is the most widely used, since it combines initialization, condition, and increment in a single line, giving clear control when the number of iterations is known in advance.

4. Which loop is faster in JavaScript?

The traditional for loop is generally the fastest, since for...in also checks inherited properties and for...of relies on iterators, both of which add slight overhead. For small to medium datasets though, the speed difference is barely noticeable.

5. Why use loops in JavaScript?

Loops let you repeat an action — like processing array elements or checking a condition — without duplicating code. This keeps programs shorter, cleaner, and easier to update later.

Success Stories

Did you enjoy this article?

Learn with HCL GUVI

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. TL;DR Summary
  2. Introduction to Loops in JavaScript
    • 1) The for Loop
    • 2) The do...while Loop
    • 3) The while Loop
    • 4) The Labeled Statement
    • 5) The break Statement
    • 6) The continue Statement
    • 7) The for...in Loop
    • 8) The for...of Loop
  3. Loops in JavaScript: Quick Comparison Table
  4. Loops vs Array Methods: forEach, map, and filter
  5. Best Practices for Using Loops
  6. Common Mistakes to Avoid
  7. Best JavaScript Courses in India 2026: Learn Loops and Core Concepts the Right Way
  8. Loops in JavaScript: Common Interview Questions
    • Q1. What does this print, and why?
    • Q2. How many times does this loop run?
    • Q3. What does continue with a label actually skip?
  9. Conclusion
  10. FAQs
    • What are the main four types of loops?
    • What are loops and arrays?
    • What is the most commonly used loop in JavaScript?
    • Which loop is faster in JavaScript?
    • Why use loops in JavaScript?