Loop

Begin Programming with JavaScript Loop

A conditional is a control flow statement. A control flow statement is something that can change the flow of a program. In this chapter, we’ll look at another control flow statement called loop.

A loop controls how many times to run a certain portion of the code.

Use Case

To see how a loop works, we’re going to create a program that can work with any number of input data.

Using the program from chapter 2 as an example, the user has to enter two numbers to get the sum.

var userInput = prompt("Please enter two numbers:");
var inputItems = userInput.split(" ");
inputItems[0] = parseInt(inputItems[0]);
inputItems[1] = parseInt(inputItems[1]);

var sum = inputItems[0] + inputItems[1];

var outputMessage = "The sum is " + sum + ".";
alert(outputMessage);

This program would be much more useful if it accepts any number of input values, so the user can get the sum of all the numbers in the input, and it doesn’t matter how many numbers the user enters.

The Code

Make a new copy of the chapter-2 folder, and rename it to chapter-4:

chapter-2
chapter-4

A loop has a header and a body:

The header controls how many times to repeat something, and the body is the code to be repeated. This specific type of loop is called a for loop, and it starts with a for keyword.

The for loop is useful for working with array.

We are going to use a for loop to repeatedly add each item in the array to the sum:

// CHANGE ↓
let userInput = prompt("Please enter the numbers:");

let inputItems = userInput.split(" ");

// CHANGE ↓
let sum = 0;

// ADD ↓
for(let i = 0; i < inputItems.length; i++){
  sum = sum + parseInt(inputItems[i]);
}

var outputMessage = "The sum is " + sum + ".";
alert(outputMessage);

unpack:

Initialize sum to 0. We need the sum to contain a number before we can add numbers to it inside the loop.

A variable i is created in the header, and it’s set to 0.

The header has three parts. They will be explained one by one in a moment.

Body

A for loop tells the computer to repeatedly run the code in the body. But with each repetition, the variable i will be different. On the first repetition, i will be 0, and on the second repetition, i will be 1, et cetera, et cetera.

Depending on the value of i, the loop will either continue or stop after each repetition.

In the body, we use i to get an item from the array and add that item to sum.

Since the i variable will be different on each repetition, inputItems[i] in turn represents a new item on each repetition.

The header is a three-part structure that controls the loop.

The first part is an assignment statement. It controls where i begins. In this example, it starts with 0 to match the index of the first item of the array.

The second part is a condition that controls when the loop should stop.

This is a condition just like the ones we use in conditionals but with a different operator. The condition will be true if i is smaller than the size of the array. And if the condition is true, the loop will keep repeating. If the condition becomes false, the loop will stop immediately.

It’s important to be aware that the length of an array is not the index of the last item in the array. length is actually 1 greater than the last index.

So when i is at the last index, the condition will still be true, because it’s still less than the length.

The last part of the header is for making i different on each repetition. If i doesn’t change, it will remain 0 forever and the loop will not be useful at all.

The double plus ++ is called an increment operator, it’s used for adding 1 to a variable. It’s a shorthand for writing i = i + 1.


Together, the three parts control:

  • the number of times the loop should run,
  • and the value of i at each time.

Flow

Let’s take a look at the flow of a for loop.

unpack:

The variable i only gets initialized once.

On each cycle, the condition gets checked first, then the code in the body is run, and finally, it jumps back to the header to increment i.

configurations

A for loop doesn’t have to start at 0 and stop after the last item in the array. But because a for loop is often used with an array, i is usually initialized as 0, and the condition is often based on the length of an array.

We can also customize the header to add 2 for each cycle by replacing i++ with i=i+2, and this will have the effect of skipping every other number. But i++ is usually what you need when working with an array.

And finally, i is just a variable name, so we can call it whatever we want. Most programmers prefer to use the name i, because it’s short for index.

Rehash

Now that we’ve seen all the pieces of a for loop, let’s take a look at another example.

This program uses alert five times with a different message each time:

alert("first");
alert("second");
alert("third");
alert("fourth");
alert("fifth");

We can use a for loop to rewrite the program:

let ordinalNums = ["first", "second", "third", "fourth", "fifth"];

for(let i=0; i<ordinalNums.length; i++){
  alert(ordinalNums[i]);
}

The version with the loop seems more complicated, but it’s more productive for the long run. Imagine you have to add five more messages:

alert("first");
alert("second");
alert("third");
alert("forth");
alert("fifth");
alert("sixth");
alert("seventh");
alert("eighth");
alert("ninth");
alert("tenth");

With the loop version, we just need to add the five new string values to the messages array:

let ordinalNums = [
  "first", "second", "third", "forth", "fifth",
  "sixth", "seventh", "eighth", "ninth", "tenth"
];

for(let i=0; i<ordinalNums.length; i++){
  alert(ordinalNums[i]);
}

You don’t have to save this as a new file to try out the code. As a quick alternative, you can copy and paste it in the console, and hit enter to run the code.

image

Loop and Conditional

Next, we’ll use conditional and loop together in the same program.

↓ Back to our main program:

let userInput = prompt("Please enter the numbers:");
let inputItems = userInput.split(" ");

let sum = 0;

for(let i = 0; i < inputItems.length; i++){
  sum = sum + parseInt(inputItems[i]);
}

var outputMessage = "The sum is " + sum + ".";
alert(outputMessage);

Imagine that the user accidentally enters a word or a character that is not a number. In that case, it would be more intuitive to ignore that item and carry on with the rest of the valid items.

In the body of the loop, we need to make sure that the item is a valid number before adding it to the sum.

...
for(let i = 0; i < inputItems.length; i++){
  let num = parseInt(inputItems[i]);
  if(!isNaN(num)){ // ← NEW
    sum = sum + num;
  } // ← NEW
}
...

not a number

Let’s take a closer look at the condition:

!isNaN(num)

↓ The parseInt function will return a special value NaN if the item is not a number. NaN is an abbreviation for not a number.

And then we take the return value from parseInt and send it to isNaN.

isNaN stands for Is Not a Number? It’s a function that returns true if the parameter is the special value NaN. And it returns false if the parameter is a number. The parameter can be other values too, but we will only be using it with either a number or NaN.

↓ For this program, we want the condition to be true if the item is a number. We can use the negation operator to flip the condition.

This operator returns the opposite of a boolean value. In this case, it will give us the opposite of what isNaN returns. If isNaN returns true, the condition will be false.

Basically, !isNaN(num) will be true if num is a number.

Recap

let userInput = prompt("Please enter the numbers:");
let inputItems = userInput.split(" ");

let sum = 0;

for(let i = 0; i < inputItems.length; i++){
  let num = parseInt(inputItems[i]);
  if(!isNaN(num)){
    sum = sum + num;
  }
}

var outputMessage = "The sum is " + sum + ".";
alert(outputMessage);
  • A for loop has a header and a body.
  • The body is the code to be repeated; The header controls how many times the body repeats.
  • The i variable in the loop will be different on each repetition; We can use the i to get an item from the array on each repetition.
  • We put a conditional inside the loop to make sure that an input item is valid before adding it to the sum.

The main benefits of using a loop are to be able to work with a flexible amount of input values, and to write the code only once but repeat it automatically on different values.

Exercise

Try to rewrite the following code with a loop to avoid repeating parseInt and prompt five times.

let nums = [];
nums[0] = parseInt( prompt("Please enter the first number:"));
nums[1] = parseInt( prompt("Please enter the second number:"));
nums[2] = parseInt( prompt("Please enter the third number:"));
nums[3] = parseInt( prompt("Please enter the fourth number:"));
nums[4] = parseInt( prompt("Please enter the fifth number:"));
let sum = nums[0] + nums[1] + nums[2] + nums[3] + nums[4];
alert("The sum is " + sum);

unpack:

This program asks the user for five numbers, and output the sum of those numbers.

Solution

let ordinalNums = [ "first", "second", "third", "fourth", "fifth" ];

let sum = 0;

for(let i=0; i<5; i++){
  let num = prompt("Please enter the " + ordinalNums[i] + " number:");
  num = parseInt(num);
  sum = sum + num;
}

alert("The sum is " + sum);

unpack:

The sum is initialized to 0 right before the loop.

We’re using i<5 instead of using an array length because we already know how many times the loop has to repeat. The loop will always run exactly 5 times, so we don’t have to rely on any user input for that.

Alternatively, you can also use i<=4 to do the same thing.