JavaScript Loops: For, While, and Enhanced Loops

Topic Overview

Greetings, Explorer! In this lesson, we will delve into the essential tools of JavaScript loops. Loops in programming simplify and enhance the efficiency of repetitive tasks — much like a coffee maker brewing multiple cups with a single press, they automate the process, ensuring each cup is brewed quickly and consistently. In this lesson, we will explore the universe of looping in JavaScript and gain hands-on experience by applying loops to JavaScript arrays and strings.

Understanding Looping

Imagine listening to your favorite song on repeat. That's the concept of loops in programming. For instance, we can use a for loop to print greetings for a group of friends.

let friends = ["Alice", "Bob", "Charlie", "Daniel"];

for (let i = 0; i < friends.length; i++) {
    // `i` is the index that changes with each iteration
    // For each friend, print the greeting
    console.log("Hello, " + friends[i] + "! Nice to meet you.");
}

// Output:
// Hello, Alice! Nice to meet you.
// Hello, Bob! Nice to meet you.
// Hello, Charlie! Nice to meet you.
// Hello, Daniel! Nice to meet you.

Loops enable us to execute repetitive sequences automatically and efficiently.

For Loop in JavaScript

The for loop is a control flow statement that allows code to be executed repeatedly.

The structure of a for loop is typically for (initialization; condition; iteration) { loop body }, where the loop body gets executed for as long as the condition evaluates to true. After each loop, the iteration is executed, which generally updates the value of the loop control variable. Here is how it generally works:

  1. Initialization: This is where you set up the loop variable. It's executed once when the loop begins.
  2. Condition: This Boolean expression determines if the loop will continue or stop. If it's true, the loop continues; if it's false, the loop ends, and the flow jumps to the next statement after the loop block.
  3. Iteration: This is where you update the loop variable. This statement executes after the loop body and right before the next condition check.
  4. Loop Body: The block of code to be executed in each loop.

Let's print a range of numbers using a for loop:

JavaScript
for (let num = 0; num < 5; num++) {
    console.log(num);
}

// Output:
// 0
// 1
// 2
// 3
// 4

In each cycle of the loop, the variable num is updated after executing the code inside the block.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal