JavaScript Loops and Iteration: How They Work with Examples

JavaScript Loops and Iterations

You use loops in JavaScript to repeat code without copying it many times. This helps when you handle lots of data or repeat a task until something changes. You write the code once and the loop runs it as needed.

What Are Loops in JavaScript?

A loop runs the same code repeatedly. You use it to check a list or repeat steps. You write the code once and set a rule to tell the loop when to stop.

JavaScript gives you a few types of loops:

  • for repeats a set number of times
  • while runs while a rule stays true
  • do…while runs once then repeat if the rule stays true
  • for…of goes through items in an array or other list
  • for…in checks each property in an object

Each one works best in different cases. They all help you write less code and keep things simple.

How Loops Work

A loop checks a condition and runs code while the condition is true. Each time the code runs and counts as one iteration. The loop detects and checks the iteration again after each run. The loop runs again if the condition stays true. It stops if not.

You can break it down into five steps:

  1. Start and set an initial value (like a counter).
  2. Check and test a condition (like is the counter less than 5?).
  3. Run the code block if the condition is true.
  4. Update the value (like you increase the counter).
  5. Repeat and go back to step 2 and check again.

The loop runs until the condition turns false.

Here is an example:

for (let i = 0; i < 3; i++) {
  console.log("Count: " + i);
}

How it works:

  • Starts with i = 0
  • Checks if i < 3 → true
  • Prints the count
  • Increases i by 1
  • Repeats until i < 3 is false

Let’s move on to the following sections to understand the types of loops in JavaScript.

JavaScript for Loop

The for loop is one of the most common ways to repeat code in JavaScript. You use it when you already know how many times you want the loop to run. It handles the setup. Also, it checks and updates all in one line.

Here is the syntax:

for (initialization; condition; update) {
  // code to run each time
}
  • The “Initialization” sets the start point (let i = 0)
  • The “Condition” is checked before each loop run (i < 5)
  • Update changes the value after each run (i++)

For example:

for (let i = 1; i <= 5; i++) {
  console.log("Step " + i);
}

Output:

Step 1  
Step 2
Step 3
Step 4
Step 5

Here are the use cases:

  • It counts from one number to another
  • It repeats tasks a fixed number of times
  • The loop through arrays by index

JavaScript do…while Loop

The do...while loop runs a block of code at least once and then repeats the loop as long as a condition is true. This loop checks the condition after it runs the code.

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

For example:

let i = 1;

do {
  console.log("Count: " + i);
  i++;
} while (i <= 3);

Output:

Count: 1  
Count: 2
Count: 3

It runs at least once, even if the condition is false at the start.

Use do...while when you want something to happen once no matter what, like display a welcome message or prompt user input.

JavaScript while Loop

The while loop runs code as long as the condition stays true. It checks the condition before each loop and the code does not run if the condition is false at the start

Syntax:

while (condition) {
  // code to run
}

For example:

let i = 1;

while (i <= 3) {
  console.log("Count: " + i);
  i++;
}

Output:

Count: 1  
Count: 2
Count: 3
  • The loop runs only if the condition is true at the start.
  • You must update something inside the loop to avoid infinite loops.

Use while when you don’t know exactly how many times the loop should run, but want to keep going as long as some condition stays true.

JavaScript Labeled Loops

Labeled loops in JavaScript let you name a loop so you can control it from inside nested loops. This is useful when you want to use break or continue to affect an outer loop—not just the one you’re currently in.

Syntax:

labelName: for (initialization; condition; update) {
  // inner code
}

You can use break labelName; or continue labelName; to jump out of or continue the labeled loop.

Here is an example:

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

Output:

i = 1, j = 1  
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1

The loop stops entirely when i === 2 && j === 2 because of break outerLoop;.

Stop a Loop Early with break

The break statement lets you stop a loop before it finishes. When JavaScript sees break, it exits the loop immediately and moves on to the next line after the loop

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

Output:

1  
2

The loop stops when i reaches 3 because of break.

Here are the use cases:

  • Exit a loop when a condition is met
  • Stop the search once you find a match
  • Prevent unnecessary extra iterations

Skip to the Next Loop Turn with continue

The continue statement skips the rest of the code in the current loop iteration and jumps straight to the next turn of the loop. The loop itself doesn’t stop—it just skips over that one step.

Syntax:

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

Output:

1  
2
4
5

continue skips console.log() and moves to the next run when i is 3.

  • Skip unwanted values or conditions
  • Ignore specific items in a list
  • Let the loop continue but skip some code.

Loop Through Object Properties with for…in

The for...in loop lets you go through each key in an object. You use it when you need both the key and its value.

Syntax:

for (let key in object) {
  // code with object[key]
}

For example:

const user = {
  name: "Alice",
  age: 25,
  city: "New York"
};

for (let key in user) {
  console.log(key + ": " + user[key]);
}

Output:

name: Alice  
age: 25
city: New York
  • key holds each property name (as a text)
  • Use object[key] to get the value
  • It doesn’t work well with arrays—use for...of or for for those

Loop Through Values in an Iterable with for…of

The for...of loop is designed for looping through iterable objects like arrays or strings. It directly accesses the values of the iterable.

Syntax:

for (let value of iterable) {
  // code with value
}

Here is an example:

const numbers = [10, 20, 30, 40];

for (let num of numbers) {
  console.log(num);
}

Output:

10  
20
30
40
  • Works with (arrays, strings, maps, sets, iterable objects)
  • It gives you the values directly. You do not need to access them by index.
  • Easier to read and use than for...in for arrays or other iterable collections

Examples

Loop Through Nested Arrays with Dynamic Depth:

function loopThroughNestedArray(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      for (let j = 0; j < arr[i].length; j++) {
        console.log(arr[i][j]);
      }
    } else {
      console.log(arr[i]);
    }
  }
}

loopThroughNestedArray([1, [2, 3], 4, [5, 6]]);

This example checks each item in the array to see if it is an array. If it is, the loop goes through that nested array. You can handle different levels in a nested array without recursion this way.

Skip odd indices in a string with for...of:

let str = "JavaScript";
let result = "";
for (let [index, char] of [...str].entries()) {
  if (index % 2 !== 0) continue;
  result += char;
}
console.log(result);

This example moves through the string and skips characters at odd indexes. It uses for...of with entries() to get both index and value. If the index is odd, it skips the character with continue. The result shows every other letter.

Build a Frequency Map from an Array with for...in:

let arr = ['a', 'b', 'a', 'c', 'b', 'a'];
let frequencyMap = {};

for (let char in arr) {
  frequencyMap[arr[char]] = (frequencyMap[arr[char]] || 0) + 1;
}
console.log(frequencyMap);

This example builds a map that shows how often each character appears in the array. It loops through each index with for...in and updates the count every time it finds a character.

Loop through object properties. Create HTML elements based on each one:

const data = { name: "Alice", age: 30, city: "New York" };

for (let key in data) {
  let div = document.createElement('div');
  div.textContent = `${key}: ${data[key]}`;
  document.body.appendChild(div);
}

This example loops through an object’s properties and creates HTML <div> elements for each key and value. It uses for...in to get the properties and document.createElement to make the HTML content.

Break a Loop When a Prime Number is Found:

function isPrime(num) {
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) return false;
  }
  return num > 1;
}

for (let i = 2; i < 20; i++) {
  if (isPrime(i)) {
    console.log(`First prime number: ${i}`);
    break;
  }
}

This example loops through numbers until it finds the first prime. It uses the helper function isPrime to check each one. The loop stops with break once it finds a prime.

Wrapping Up

Loops in JavaScript help you repeat tasks and handle large data sets. Each loop works in a different way and fits a specific case. Here’s a recap:

  • Use for when you know how many times to run.
  • Use while when you don’t know the count but need to check a condition.
  • Use do...while when the code must run at least once before the check.
  • Use for...in to go through object properties.
  • Use for...of to move through values in arrays or strings.
  • Use break to stop a loop early.
  • Use continue to skip the current run and go to the next.
  • Use labeled loops to control nested loops with more precision.

What are the different types of loops in JavaScript?

JavaScript has several loop types: for, while, do...while, for...in, and for...of. Each fits a specific task. You use them to loop through arrays, check objects, or run code a set number of times.

How does a for loop work in JavaScript?

A for loop in JavaScript starts with a counter, checks a condition before each run, and updates the counter after each cycle. Use it when you know how many times to repeat.

What is the difference between while and do...while loops?

The main difference is when the condition is checked. A while loop checks before running the code. A do...while loop runs the code once before checking the condition.

How do break and continue statements function within loops?

The break statement stops the loop completely. The continue skips the current run and moves to the next one. Use them to change how the loop runs based on certain conditions.

What is the purpose of labeled loops in JavaScript?

Labeled loops let you name a loop. This helps you control nested loops by using break or continue with that name. It makes complex code easier to read and manage.

How can I iterate over object properties in JavaScript?

To loop through an object’s properties, use the for...in loop. It goes through all enumerable properties, giving you access to both property names and their values.

What is the difference between for...in and for...of loops?

The for...in loop goes through an object’s keys (property names). The for...of loop goes through values in iterable objects like arrays, strings, or maps.
Previous Article

PHP strtoupper Function: Convert Strings to Uppercase

Next Article

Ajax and PHP: How Ajax Works with PHP with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.