JavaScript Basics

JavaScript Loops

Master repetition and iteration in JavaScript. Learn to use for loops, while loops, modern loop methods, and control flow to efficiently process data and create patterns.

What are the different loops in JavaScript?

Use for…of to loop over the values of an array, string or other iterable. Use a classic for (let i = 0; i < n; i++) loop when you need the index or a custom step, while when you don't know how many repetitions you need, and for…in only for an object's keys. For transforming arrays, methods like map, filter and forEach are often clearer.

for (const fruit of ["apple", "kiwi"]) console.log(fruit);

for (let i = 0; i < 3; i++) console.log(i);   // 0 1 2

let n = 3;
while (n > 0) { n--; }

for (const key in { a: 1, b: 2 }) console.log(key);   // "a" "b"

For Loops

For loops are perfect when you know exactly how many times you want to repeat something. They have three parts: initialization, condition, and increment/decrement.

Basic Syntax

for (initialization; condition; increment) {
  // Code to repeat
}

Initialization: Runs once at the start

Condition: Checked before each iteration

Increment: Runs after each iteration

Common Examples

Count Up

for (let i = 1; i <= 5; i++) {
  console.log(i); // 1, 2, 3, 4, 5
}

Count Down

for (let i = 5; i >= 1; i--) {
  console.log(i); // 5, 4, 3, 2, 1
}

Array Processing

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

Real-World Example: Processing Shopping Cart

const cart = [
  {name: "Laptop", price: 999},
  {name: "Mouse", price: 25},
  {name: "Keyboard", price: 75}
];

let total = 0;
for (let i = 0; i < cart.length; i++) {
  total += cart[i].price;
  console.log(`Item: ${cart[i].name} - $${cart[i].price}`);
}
console.log(`Total: $${total}`); // Total: $1099

While Loops

While loops continue running as long as a condition is true. They're perfect when you don't know exactly how many iterations you need.

While Loop

while (condition) {
  // Code to repeat
  // Don't forget to update condition!
}

Example: Countdown

let count = 3;
while (count > 0) {
  console.log(count);
  count--; // Important!
}

Do-While Loop

do {
  // Code runs at least once
} while (condition);

Example: User Menu

let choice;
do {
  choice = prompt("Enter 1-3:");
} while (choice < 1 || choice > 3);

When to Use Which

Use While When:

  • • You don't know how many iterations needed
  • • Waiting for user input or external condition
  • • Processing until a specific value is found
  • • Reading files until end is reached

Use Do-While When:

  • • Code must run at least once
  • • User menus and input validation
  • • Game loops that need initial setup
  • • Processing that requires one attempt minimum

Infinite Loop Warning

Always make sure your loop condition will eventually become false, or your program will freeze!

Modern Loop Methods (ES6+)

Modern JavaScript provides cleaner, more readable ways to iterate through arrays and objects. These methods are often preferred for their simplicity and safety.

for...of Loop

for (const item of array) {
  console.log(item);
}

Arrays

const fruits = ['apple', 'banana'];
for (const fruit of fruits) {
  console.log(fruit);
}

Strings

for (const char of "Hello") {
  console.log(char); // H, e, l, l, o
}

for...in Loop

for (const key in object) {
  console.log(key, object[key]);
}

Objects

const user = {name: 'Alice', age: 25};
for (const key in user) {
  console.log(key + ':', user[key]);
}

⚠️ Arrays (Not Recommended)

// Gets indices, not values
for (const index in [1,2,3]) {
  console.log(index); // "0", "1", "2"
}

Quick Reference: Which Loop to Use

for...of

Arrays, strings, iterables (values)

for...in

Objects (keys/properties)

Traditional for

When you need the index

Loop Control: break & continue

Sometimes you need to change how loops behave - skip certain iterations or exit early. The `break` and `continue` statements give you this control.

break Statement

Exits the loop completely

for (let i = 1; i <= 10; i++) {
  if (i === 5) {
    break; // Exit loop
  }
  console.log(i); // 1, 2, 3, 4
}

Finding First Match

const users = ['Alice', 'Bob', 'Charlie'];
for (const user of users) {
  if (user === 'Bob') {
    console.log('Found Bob!');
    break; // Stop searching
  }
}

continue Statement

Skips current iteration, continues with next

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue; // Skip 3
  }
  console.log(i); // 1, 2, 4, 5
}

Skip Invalid Items

const numbers = [1, -2, 3, -4, 5];
for (const num of numbers) {
  if (num < 0) continue; // Skip negatives
  console.log(num); // 1, 3, 5
}

Real-World Example: Data Processing

const products = [
  {name: 'Laptop', price: 999, inStock: true},
  {name: 'Phone', price: 599, inStock: false},
  {name: 'Tablet', price: 299, inStock: true},
  {name: 'Watch', price: 199, inStock: true}
];

let totalValue = 0;
let itemsProcessed = 0;

for (const product of products) {
  // Skip out-of-stock items
  if (!product.inStock) {
    console.log(`Skipping ${product.name} - out of stock`);
    continue;
  }

  totalValue += product.price;
  itemsProcessed++;

  // Stop if we've processed enough items
  if (itemsProcessed === 3) {
    console.log('Processed maximum items');
    break;
  }
}

console.log(`Total value: $${totalValue}`); // Total value: $1497

Nested Loops

Nested loops allow you to create complex patterns and process multi-dimensional data. Use them carefully as they can quickly become performance-intensive.

Basic Pattern Creation

for (let row = 1; row <= 3; row++) {
  let line = '';
  for (let col = 1; col <= row; col++) {
    line += '★ ';
  }
  console.log(line);
}
// Output:
// ★
// ★ ★
// ★ ★ ★

2D Array Processing

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

for (let row = 0; row < matrix.length; row++) {
  for (let col = 0; col < matrix[row].length; col++) {
    console.log(`[${row}][${col}] = ${matrix[row][col]}`);
  }
}

Common Nested Loop Patterns

Multiplication Table

for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 3; j++) {
    console.log(`${i} × ${j} = ${i * j}`);
  }
}

Finding Pairs

const letters = ['A', 'B'];
const numbers = [1, 2];

for (const letter of letters) {
  for (const number of numbers) {
    console.log(letter + number); // A1, A2, B1, B2
  }
}

Search in 2D

const grid = [[1,2], [3,4]];
const target = 3;
let found = false;

for (let row of grid) {
  for (let cell of row) {
    if (cell === target) {
      found = true;
      break;
    }
  }
  if (found) break;
}

Performance Warning

// O(n²) complexity - be careful!
for (let i = 0; i < 1000; i++) {
  for (let j = 0; j < 1000; j++) {
    // 1,000,000 iterations!
  }
}

Performance Tip

Nested loops can quickly become slow. For large datasets, consider alternative approaches like array methods or data structures.

Best Practices & Common Patterns

✅ Best Practices

Use const for loop variables

Prevents accidental reassignment

for (const item of array)

Cache array length

Improves performance in large loops

for (let i = 0, len = arr.length; i < len; i++)

Use descriptive variable names

Makes code more readable

for (const student of students)

❌ Common Mistakes

Infinite loops

Forgetting to update the condition

while (i < 10) { /* forgot i++ */ }

Using for...in with arrays

Gets indices as strings, not values

for (const item in array) // Wrong!

Modifying array while looping

Can cause skipped elements or errors

arr.splice(i, 1) // in for loop

Modern Alternatives to Consider

Array Methods

map(), filter(), reduce(), forEach()

Array.from()

Create arrays with specific patterns

Set & Map

Better data structures for some use cases

Try It Yourself

Practice with this interactive example. Try modifying the code to experiment with different loop patterns!

Code Editor

<div id="output">
  <h3>JavaScript Loops Practice</h3>
  <p>Open the console to see the output!</p>
</div>

Preview

💡 Practice Challenges

  • • Modify the for loop to count backwards from 10 to 1
  • • Add more items to the fruits array and see them in the output
  • • Create a pattern using nested loops (try making a triangle of stars)
  • • Experiment with break and continue in different scenarios
  • • Try creating a loop that finds the largest number in an array

Loops — step by step

1 / 4
1

for vs while — when to use each

for loops are best when you know the iteration count in advance: for (let i = 0; i < n; i++). while loops are best when the exit condition depends on something that changes during iteration — processing a queue, reading a stream, game loops. do...while guarantees at least one execution — useful for menu prompts and retry logic.

1 of 4
🔍for...of with index — use entries()
When you need both the index and the value in a for...of loop, use array.entries(): for (const [i, val] of arr.entries()). This gives you index i and value val without falling back to a traditional for loop. Similarly, Map.entries() gives [key, value] pairs.

🎯 Quick Check

Why should you avoid for...in to iterate over an array?

JavaScript Loops: summary

Key points

  • break exits the loop; continue skips to the next iteration.
  • Don't use for…in on arrays: it iterates keys as strings and includes inherited properties.
  • Make sure a while loop's condition eventually becomes false, or it runs forever and freezes the tab.
  • for…of with array.entries() gives you both index and value: for (const [i, v] of arr.entries()).

Frequently asked questions

›What is the difference between for…of and for…in?

for…of gives values of an iterable (array items, string characters). for…in gives the property names (keys) of an object.

›Can I break out of forEach?

No. forEach always visits every element. Use for…of with break, or some()/find(), which stop early.