Conditional

Begin Programming with JavaScript Conditional

So far the programs we’ve seen are all linear. They run from top to bottom without skipping a single line of code. In this chapter, we’re going to learn how to use a conditional to select and run certain parts of the code depending on the input value.

image

But first, let’s talk about why that would be useful.

use case

Take the example from the previous chapter, we are simply adding two numbers together. But what if we want the user be able to choose between add, subtract, multiply, and divide?

image

That’s four possible ways a program can be run, and it all depends on what the user chose.

image

So if the user chose add, we will run the code for addition, and skip all the code related to subtract, multiply and divide.

image

the code

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

chapter-2
chapter-3

↓ First, modify the program to accept three input items. The first item is one of the four operations the user can choose from, the second and the third items are the two numbers.

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

let inputItems = userInput.split(" ");

// CHANGE ↓
let operation = inputItems[0];
let num1 = parseInt( inputItems[1]);
let num2 = parseInt( inputItems[2]);

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

unpack:

The prompt message is changed to reflect the new requirement.

New variables are created for all three input items so that we can give them more appropriate names.

We haven’t used any conditional yet, but we set up an operation variable, and it will let the user to decide which one of the four operations the program should perform.

Conditional

We’ll make it work for addition first, and move on to the other operations later.

We will use a conditional statement, or just conditional for short. The job of a conditional is to control whether a certain part of the code should run or not.

let userInput = prompt("Please enter the operation and two numbers:");
let inputItems = userInput.split(" ");
let operation = inputItems[0];
let num1 = parseInt( inputItems[1]);
let num2 = parseInt( inputItems[2]);

// NEW ↓
if(operation === "add"){
  let sum = num1 + num2;
  let outputMessage = "The sum is " + sum + ".";
  alert(outputMessage);
}

unpack:

We’re using the if keyword to create a conditional.

We’re using let to replace var; We’ll talk about what let is in a bit.

A conditional has two parts: the condition and the code inside the code block.

right

The condition decides whether the code should run or not.

Condition

The condition we’re using is a comparison between the operation variable and a string value. We’re comparing two items to see if they are equal, and we’re using the equality operator === to do that. The comparison will produce a boolean value.

right

A boolean is a value that can be either true or false. If the two items are equal, the comparison will produce a true value, otherwise, a false value.

If we have a true value as the condition, the code inside the block will be run, otherwise, it will be ignored.

Basically, this is saying, if the operation the user chose is equal add, go ahead and run the code in the block.

let

Both let and var are keywords for creating variables. But a variable created using let inside a block will only be available inside that block.

right

We will be getting an error if we ever use it outside that block. Getting an error, in this case, is a good thing because it helps us to detect potential problems.

let can also be used outside a code block just like var. So we can actually use let to replace var altogether. For simplicity, I’ll be using let instead of var from now on.

let userInput = prompt("Please enter the operation and two numbers:");
let inputItems = userInput.split(" ");
let operation = inputItems[0];
let num1 = parseInt( inputItems[1]);
let num2 = parseInt( inputItems[2]);

if(operation === "add"){
  let sum = num1 + num2;
  let outputMessage = "The sum is " + sum + ".";
  alert(outputMessage);
}

unpack:

All the code (so far)

You can save the program and try it out. If you submit add 1 2 as input, the program will give you 3. If you don’t have add in the input, the program will not do anything.

else

Currently, the program only supports addition, we’ll make it work for the other operations later. But for now, when the user enters something that doesn’t have add, we should tell the user that the program only supports add.

image

...

if(operation === "add"){
  let sum = num1 + num2;
  let outputMessage = "The sum is " + sum + ".";
  alert(outputMessage);
}
else {
  let outputMessage = "You need to enter the \"add\" operation and two numbers.";
  alert(outputMessage);
}

unpack:

Each alternative is called a branch. We’re using a new keyword else to create the second branch.

In order to show quotation marks to the user, we have to prefix each quotation mark with a slash.

This combination of if and else is a common way to use conditional for an either-or situation.

The slash will not appear in the popup box.

image

It’s for distinguishing between the quotation marks that we want to show to the user and the quotation marks that create the string.

right

else if

The program is not complete yet. We still need to make it work with subtraction, multiplication, and division.

...
if(operation === "add"){
  let sum = num1 + num2;
  let outputMessage = "The sum is " + sum + ".";
  alert(outputMessage);
}
else if(operation === "subtract"){
  let difference = num1 - num2;
  let outputMessage = "The difference is " + difference + ".";
  alert(outputMessage);
}
else if(operation === "multiply"){
  let product = num1 * num2;
  let outputMessage = "The product is " + product + ".";
  alert(outputMessage);
}
else if(operation === "divide"){
  let quotient = num1 / num2;
  let outputMessage = "The quotient is " + quotient + ".";
  alert(outputMessage);
}
else{
  let outputMessage = "You didn't specify an operation.";
  alert(outputMessage);
}

unpack:

The first branch starts with if, and the last branch starts with else. Everything in-between is else if.

Each else if branch requires a condition just like the if branch does. We don’t need a condition for the else branch because it’s meant to be a safety net when all the previous conditions are false.

The message in the else branch has been modified.

All five branches are grouped together as a single conditional structure, but only one branch will get chosen.

The code will still get processed from top to bottom. So the first condition will get checked first, and if it’s false, the computer will skip the first block and move on to the second condition. This means conditions can overlap, but only the first true condition gets chosen.

DRY

DRY is an important programming principle; It stands for Don’t Repeat Yourself.

↓ We repeated the same alert statement in every branch. Whenever possible, we should avoid code repetitions.

right

↓ We can move the alert statement out of the conditional. And we also need to declare the outputMessage variable before the conditional, so that the variable can be used both inside and outside the conditional.

left

unpack:

The outputMessage variable is created outside the conditional and shared across all the branches. This is the first time we create a variable without giving it a value by default. This is called a declaration.

Because the outputMessage variable has already been declared outside the conditional, we can remove let inside the conditional. We only need to declare a variable once.

Recap

let userInput = prompt("Please enter the operation and two numbers:");

let inputItems = userInput.split(" ");
let operation = inputItems[0];
let num1 = parseInt( inputItems[1]);
let num2 = parseInt( inputItems[2]);

let outputMessage;

if(operation === "add"){
  let sum = num1 + num2;
  outputMessage = "The sum is " + sum + ".";
}
else if(operation === "subtract"){
  let difference = num1 - num2;
  outputMessage = "The difference is " + difference + ".";
}
else if(operation === "multiply"){
  let product = num1 + num2;
  outputMessage = "The product is " + product + ".";
}
else if(operation === "divide"){
  let quotient = num1 + num2;
  outputMessage = "The quotient is " + quotient + ".";
}
else{
  outputMessage = "You didn't specify an operation.";
}

alert(outputMessage);

unpack:

All the code

  1. We get the input value by using prompt.
  2. Split the input value into three items.
  3. Create a variable for each of the three items.
  4. Create an outputMessage variable without a value.
  5. Set up a conditional with five branches, and use the first input item for the conditions. Depending on the condition, we set the outputMessage variable with a different message.
  6. Show the output message to the user.

Exercise

Make a new copy of the chapter-3 folder, and rename it to chapter-3-ex:

chapter-3
chapter-3-ex

Modify the conditional to accept squaring a number. This is different from other operations because it only takes one number.

Input:

square 2

Output:

The square is 4.

Solution

...
if(operation === "add"){
  let sum = num1 + num2;
  outputMessage = "The sum is " + sum + ".";
}
else if(operation === "subtract"){
  let difference = num1 - num2;
  outputMessage = "The difference is " + difference + ".";
}
else if(operation === "multiply"){
  let product = num1 + num2;
  outputMessage = "The product is " + product + ".";
}
else if(operation === "divide"){
  let quotient = num1 + num2;
  outputMessage = "The quotient is " + quotient + ".";
}
else if(operation === "square"){ // NEW
  let square = num1 * num1;
  outputMessage = "The square is " + square + ".";
}
else{
  outputMessage = "You didn't specify ion";
}
...