JavaScript - 8

JavaScript - 8: Loops (for loop)

Loops let JavaScript repeat instructions without writing the same code again and again.

In this lesson, you will use a for loop to move through an array of numbers and print each number along with its square.

Your challenge: Loop through the numbers array and print a message for every item, such as 5 squared is 25.

✦ JavaScript Editor
▶ Live Output

What is a loop?

A loop repeats a block of code.

Without a loop, you might have to write: console.log(numbers[0]);, then console.log(numbers[1]);, then console.log(numbers[2]);, and so on.

A loop lets JavaScript handle those repeated steps for you.

The basic for loop

A common for loop looks like this: for (let i = 0; i < numbers.length; i++)

There are three important parts inside the parentheses.

1. let i = 0
The loop starts with i equal to 0.

This is useful because array indexes also begin at 0.

2. i < numbers.length
The loop keeps running while i is smaller than the number of items in the array.

If the array has five items, its length is 5, so the valid indexes are 0 through 4.

3. i++
After each loop, i increases by one.

So the values of i become: 0, 1, 2, 3, and 4.

Use i as the array index

Inside the loop: numbers[i] means "get the item at the current index."

On the first loop, i is 0, so JavaScript reads: numbers[0]

On the next loop, i becomes 1, so JavaScript reads: numbers[1]

This continues until every item has been visited.

Calculate the square

To square a number, multiply it by itself: number * number

Inside this loop, that becomes: numbers[i] * numbers[i]

For example, if the current number is 8, the calculation is: 8 * 8 which gives 64.

Make the output readable

You can use a template literal to combine the number and its result: `${numbers[i]} squared is ${numbers[i] * numbers[i]}`

Then pass that message to console.log().

Experiment: Add another number to the array.

For example: let numbers = [2, 5, 8, 10, 3, 12];

You should not need to change the loop. Because it uses numbers.length, it automatically adjusts to the new array size.

Try changing the starting value:

Temporarily change: let i = 0 to: let i = 1

Run the code again and notice which array item is skipped. Then change it back to 0.

Why use < instead of <=?

If an array has five items, numbers.length is 5, but the final valid index is 4.

That is why: i < numbers.length is the usual pattern.

If you used: i <= numbers.length the loop would try to access one position beyond the end of the array.

Extra experiment: Create another array such as: let temperatures = [18, 21, 25, 19];

Use a loop to print: Temperature: 18, Temperature: 21, and so on.

Good JavaScript habit: When looping through an array by index, use the array's .length instead of manually typing the number of items. That way the loop continues to work if the array changes.

👀 Show Solution
let numbers = [2, 5, 8, 10, 3];

for (let i = 0; i < numbers.length; i++) {
  let number = numbers[i];
  let square = number * number;

  console.log(`${number} squared is ${square}`);
}

The loop begins at index 0 and continues while i is smaller than numbers.length.

On every loop, the current array item is stored in number, its square is calculated, and the result is printed.