JavaScript Beginner Day 5: Loops

Goal of this Day

Today you will learn:

By the end, you will be able to automate repetitive tasks in JavaScript.

Step 1: Why Loops?

Loops are used to repeat code multiple times.

Example:

Step 2: for Loop

The for loop runs a specific number of times.


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

Explanation:

Step 3: while Loop

The while loop runs as long as a condition is true.


let i = 1;

while (i <= 5) {
  console.log(i);
  i++;
}

Practice


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

Task

Complete the following tasks:

Example:


// 1 to 10
for (let i = 1; i <= 10; i++) {
  console.log(i);
}

// Even numbers
for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) {
    console.log(i);
  }
}