Launch Into Loops: Overview and Goals

Hello, space explorer! Today, we're diving into JavaScript loops. Loops automate repetitive code. In this lesson, we'll cover two types of loops: for and while, and their usage in creating a dynamic HTML list.

Introduction to JavaScript Loops

Loops are all about repetition. Think about your morning routine of brushing your teeth — back and forth until they are all clean. That's a loop! In JavaScript, there are two types of loops: for and while. Let's get started!

Singularly Stepping into the "for" Loop

In a for loop, you're aware of the loop's iterations. Its syntax includes initialization, condition, and update.

for (initialization; condition; update) {
  // code to loop over
}

For instance, let's say we want to print numbers from 1 to 5:

for (let i = 1; i <= 5; i++) {
  console.log(i); // prints the number
}

Here, we initialize i to 1, ensure i is less than or equal to 5, and increment i by 1 after each loop. The loop stops when i > 5.

Wandering In the "while" Loop

Next, we explore the while loop, which continues for as long as a certain condition is true.

Here’s the syntax:

while (condition) {
  // code to loop over
}

As an example, consider a countdown from 5 to 0:

let countdown = 5;
while (countdown >= 0) {
  console.log(countdown); // prints the countdown number
  countdown--;
}

Here, as long as countdown is greater than or equal to 0, we print the countdown number and decrement it by 1.

Dynamic Lists in an HTML Page With Loops

Loops generate dynamic content in HTML pages. Just imagine dynamically creating a list of planet names:

<body>
  <ul id="planet-list"></ul>
</body>
const planets = ["Earth", "Mars", "Venus", "Jupiter", "Saturn"];
let listHTML = '';
for (let i = 0; i < planets.length; i++) {
  listHTML += '<li>' + planets[i] + '</li>'; // creates a list item for each planet
}

// Displays the list on the webpage by taking the element with the id "planet-list" and updating its content.
document.getElementById("planet-list").innerHTML = listHTML;

// This console log will print the final HTML string that represents the list of planets.
console.log(listHTML); // Will print <li>Earth</li><li>Mars</li><li>Venus</li><li>Jupiter</li><li>Saturn</li>

We've managed to create a dynamic list of planets!

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