[JS Basics] Loops in JavaScript: A Detailed Guide for Beginners

Have you ever had to do a repetitive task in real life? Like packing 100 boxes, sending 50 identical emails, or simply counting from 1 to 1000. It's tedious and time-consuming, right?

In programming, we often face similar repetitive tasks. Fortunately, JavaScript provides a powerful tool to automate these jobs: Loops.

Loops in JavaScript

Think of loops as tireless assistants, ready to execute your command hundreds, thousands, or even millions of times with perfect accuracy. In this article, we'll explore and master all types of loops in JavaScript, from the basics to advanced techniques and modern approaches. 🚀

Why do we need loops?

Before diving into syntax, let's see why loops are indispensable.

Suppose you want to display numbers from 1 to 5 in the console. Without loops, you'd write:

console.log(1)
console.log(2)
console.log(3)
console.log(4)
console.log(5)

Easy, right? But what if you need to display numbers from 1 to 1000? Copying and pasting 1000 lines of code would be a nightmare. This is where loops shine.

With a for loop, you can solve the problem in just 3 lines:

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

Short, clean, and efficient. Loops help us:

  • Save time and effort writing code.
  • Reduce errors from copy/paste.
  • Make code more readable and maintainable.
  • Handle large datasets flexibly without knowing the number of elements in advance.

Common types of loops in JavaScript

JavaScript offers several types of loops, each with its own strengths and suited for specific situations.

1. for loop – Your reliable companion

This is the most common and widely used loop. The for loop is ideal when you know exactly how many times you want to repeat a block of code.

Syntax:

for (initialization; condition; increment) {
  // Code block to execute
}
  • initialization: Runs once before the loop starts. Usually used to declare and assign a counter variable (e.g., let i = 0).
  • condition: Checked before each iteration. If true, the code block executes. If false, the loop ends.
  • increment: Runs after each iteration. Usually used to increase or decrease the counter (e.g., i++ or i--).

Example: Print even numbers from 2 to 10.

for (let i = 2; i <= 10; i += 2) {
  console.log(`Current even number: ${i}`)
}
// Output:
// Current even number: 2
// Current even number: 4
// ...
// Current even number: 10

âś… When to use? When you know the number of iterations in advance, such as iterating over an array of known length.

2. while loop – When you don't know the end point

The while loop executes a block of code as long as a specific condition is true. It's useful when you don't know the number of iterations in advance and rely on a condition.

Syntax:

while (condition) {
  // Code block to execute
}

Example: A simple game where the user guesses a number.

let secretNumber = 7
let guess = 0

while (guess !== secretNumber) {
  guess = parseInt(prompt('Guess a number from 1 to 10:'))
  if (guess !== secretNumber) {
    alert('Wrong, try again!')
  }
}

alert('Congratulations! You guessed the secret number 7!')

⚠️ Warning: Be careful with while. If the condition never becomes false, you'll create an infinite loop, which can freeze your browser or program.

âś… When to use? When the number of iterations is unknown and depends on a condition (e.g., reading from a stream, waiting for user input).

3. do...while loop – Execute at least once

The do...while loop is similar to while, but with one key difference: the code block inside do will execute at least once before checking the condition.

Syntax:

do {
  // Code block to execute
} while (condition)

Example: Build a menu that asks the user for a choice until they select "Quit".

let choice

do {
  choice = prompt("Menu:\n1. View products\n2. Add to cart\nEnter 'q' to quit.")
  // Handle choice here...
  console.log(`You chose: ${choice}`)
} while (choice !== 'q')

console.log('Thank you for using the program!')

âś… When to use? When you need to ensure the code block runs at least once, regardless of the initial condition.

4. for...of loop – Modern way to iterate collections

Introduced in ES6, for...of provides a very simple and clean way to loop through elements of iterable objects like Array, String, Map, Set, ...

Syntax:

for (const element of iterable) {
  // Code block to execute with each 'element'
}

Example: Iterate through an array of fruits.

const fruits = ['Apple', 'Banana', 'Orange']

for (const fruitName of fruits) {
  console.log(`I like to eat ${fruitName}`)
}
// Output:
// I like to eat Apple
// I like to eat Banana
// I like to eat Orange

đź’ˇ This is the recommended way to iterate arrays instead of the traditional for loop because it's concise and less error-prone.

5. for...in loop – For objects only

The for...in loop is used to iterate over the properties of an object.

Syntax:

for (const key in object) {
  // Code block to execute with each 'key'
}

Example: List information of a user.

const user = {
  name: 'An',
  age: 25,
  job: 'Developer',
}

for (const property in user) {
  console.log(`${property}: ${user[property]}`)
}
// Output:
// name: An
// age: 25
// job: Developer

⚠️ Important note: Never use for...in to iterate arrays. It may loop through unwanted properties (e.g., those added to Array.prototype) and the order is not guaranteed. Use for...of for arrays.

Controlling loop flow: break and continue

Sometimes, you don't want to run the entire loop. JavaScript provides two statements to control execution flow:

  • break: Exit the loop immediately.
  • continue: Skip the current iteration and move to the next one.

Example: Find the first even number greater than 5 in an array and skip odd numbers.

const numbers = [1, 2, 3, 4, 6, 7, 8]

for (const num of numbers) {
  if (num % 2 !== 0) {
    continue // Skip if odd
  }

  if (num > 5) {
    console.log(`Found the first even number greater than 5: ${num}`)
    break // Exit the loop
  }

  console.log(`Checking even number: ${num}`)
}
// Output:
// Checking even number: 2
// Checking even number: 4
// Found the first even number greater than 5: 6

Modern array iteration methods

In modern JavaScript, especially when working with arrays, we often prefer using built-in array methods over traditional loops. These methods make code more expressive, readable, and concise.

  • forEach(): Executes a function for each array element. Similar to for...of but you can't use break or continue.

    const fruits = ['Apple', 'Banana']
    fruits.forEach((fruit) => console.log(fruit))
    
  • map(): Creates a new array by transforming each element of the original array.

    const numbers = [1, 2, 3]
    const squared = numbers.map((number) => number * number) // squared is [1, 4, 9]
    
  • filter(): Creates a new array containing elements that satisfy a condition.

    const numbers = [1, 2, 3, 4, 5]
    const evens = numbers.filter((number) => number % 2 === 0) // evens is [2, 4]
    
  • reduce(): "Reduces" the array to a single value (e.g., sum, find the largest value).

    const numbers = [1, 2, 3, 4]
    const sum = numbers.reduce((total, current) => total + current, 0) // sum is 10
    

Conclusion: Choosing the right loop

Loops are one of the pillars of programming. Understanding and mastering them will help you solve countless problems efficiently.

Quick summary of when to use what:

SituationBest choice
Iterating over arrays/stringsfor...of or array methods
Iterating over object propertiesfor...in
Looping a known number of timesTraditional for
Looping based on a condition, may not run at allwhile
Looping based on a condition, must run at least oncedo...while

Hopefully, this article has given you a comprehensive and deep understanding of JavaScript loops. Don't just read—open your code editor and practice today. Good luck on your journey to mastering JavaScript!

Related Posts

[JS Basics] What is JavaScript? Why is it Important for Developers?

What is JavaScript? This article explains in detail the concept, role, and applications of JavaScript—the indispensable programming language in modern web development.

[JS Basics] Functions in JavaScript: Concepts, Declarations, and Detailed Examples

Discover the power of Functions in JavaScript! Step-by-step guide on how to write and use functions effectively. Start learning now to level up your coding skills.

[JS Basics] Operators in JavaScript: Overview and Easy-to-Follow Practical Examples

Want to master JavaScript? Start by understanding the basic operators. This detailed guide will help you get familiar with the most common types of operators, from arithmetic to logic, with real-world examples.

[JS Basics] How to Set Up a JavaScript Runtime Environment

Are you new to programming and want to start with JavaScript? This article will guide you step-by-step on how to set up a JavaScript runtime environment on your computer easily and quickly.