Conditional

Begin Programming with JavaScript Conditional

Text Version

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 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 to let the user 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.

The operation variable will be used 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 brackets.

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 data type that can only be 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 vs var

Both let and var are keywords for creating variables. But the variables created with let inside a block are only available inside that block.

right

Having this restriction can help with preventing programming bug.

If the variable is created using let inside a block, 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 informs us that the code might have 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.

Finishing Up

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

Each alternate route is called a branch. And since the user can always enter something that we didn’t expect, we need an extra branch to handle situations like that. So in total, we need four more branches.

...
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 always starts with if, and the last branch should start 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. So usually, the else branch is used for guarding against unacceptable input values.

The else branch in this case only prepares an output message.

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 of code 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.

↓ The alert statement is repeated 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 it’s available both inside and outside the block.

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.

Since the outputMessage has already been declared outside the conditional, we can remove let in each branch.

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. Set up a conditional with five branches using the first input item for the conditions.
  4. 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 branches in that it doesn’t need the second 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";
}
...