Introduction and Overview

Welcome to our journey through JavaScript's for loops - powerful tools for automating repeatable tasks. Using simple examples, we'll explore the For Loop, For-In Loop, and For-Of Loop. Let's get started!

Introduction to JavaScript 'For' Loops

Essentially, loops execute tasks repeatedly, akin to playing a favorite song on repeat. Here's a simple for loop that prints numbers from 1 to 5:

for (let i = 1; i <= 5; i++) {
    console.log(i); // Will print numbers from 1 to 5
}
/*
Prints:
1
2
3
4
5
*/

In this example, we initialize i as 1, set our condition as i <= 5, and increment i by 1 in each iteration with i++. So, i goes from 1 to 5, and every time, we print the current value of i to the console.

Note: i++ is an increment operation that increases the value of i by 1. It basically the same as i = i + 1 or i += 1, just in a shorter form.

Deep Dive into 'For' Loop

Let's look at our example once again:

for (let i = 1; i <= 5; i++) {
    console.log(i); // Will print numbers from 1 to 5
}

The For Loop comprises three elements:

  • Initialization: Here, i starts at 1.
  • Condition: The loop persists as long as i <= 5.
  • Changes: Here, i++ increases i by 1 each loop iteration.
    • Changes can be anything, we could also decrease i by 1 every time if that would make more sense.

The structure of the loop is always as follows:

for ([initialization]; [condition]; [changes]) {
    [loop body]
}

Consider, for instance, how we might list all seven days of the week:

let days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
for (let i = 0; i < days.length; i++) { // 'i' goes through all 'days' list indices
    console.log(days[i]); // Prints each day of the week onto the console
}
/*
Prints:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
*/
Exploring 'For-In' Loop

A for-in loop iterates over properties of an object, similar to checking items in a backpack:

let star = {
    name: "Sun",
    color: "Yellow",
    size: "Giant",
};
for (let property in star) {
    console.log(property, '->', star[property]);
}
/*
Prints:
name -> Sun
color -> Yellow
size -> Giant
*/

In this example, property steps through each property in the star object, and star[property] retrieves the value for each property.

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