1.7 - Making decisions using “if”

We get Javascript to make decisions about what code to run on the basis of the true or false comparisons we were creating above. The “if” statement allows us to say to Javascript “if the answer to the comparison is true, then run this optional code”.

Here’s an example:

let sister_age = 15;
let brother_age = 12;
if (sister_age > brother_age) {
   console.log("Sister is older");

We can also tell Javascript to run some alternative code if the comparison was not true. That would look like:

let sister_age = 15;
let brother_age = 12;
if (sister_age > brother_age) {
   console.log("Sister is older");
} else {
   console.log("Brother is older");

Let’s take a moment to look at the syntax and styling of these “if” statements as there are a few things that have been introduced:

Using the above example, what happens if they are the same age?

Change the above to make the brothers age also 15. What will it print? The problem is in the way we framed the options we gave Javascript. We only gave it two options to choose from. If the sister is older than the brother, it will print “Sister is older” and in every other circumstance it will print “Brother is older”. If they are both 15, however, what we really want is for Javascript to tell us they are both the same age. To do this we can introduce another leg to the “if” statement.

Try this:

let sister_age = 15;
let brother_age = 15;
if (sister_age > brother_age) {
   console.log("Sister is older");
} else if (sister_age === brother_age) {
   console.log("Ages are the same! They might be twins!");
} else {
   console.log("Brother is older");

We are now giving Javascript a series of questions to run through. The work flow looks like this:

The general rule is:

if (comparison_is_true) {
} else if (alternative_comparison_is_true) {
} else {

Important notes:

Common mistake: Mis-matched parenthesis and braces!

Javascript uses the parenthesis and braces to tell where to start and stop evaluating your code for different uses. One of the most common errors I find when helping a student debug (error-correct) their code is they have missed a closing parenthesis or brace. If your code is not working, if in doubt, count the number of opening parenthesis/braces and check you have the right number of closing ones where you expect them to be!

Multiple “else if”s

Here’s another example that shows you can have an unending number of else if questions in your “if” statement.

(don’t worry about the first two lines. As you can probably work out, they are Javascript code that accesses the date and stores the current day of the week as a number between 0 and 6)

let today = new Date();
let day_of_week = today.getDay();
if (day_of_week === 0) {
    console.log("Today is Sunday")
} else if (day_of_week === 1) {
    console.log("Today is Monday")
} else if (day_of_week === 2) {
    console.log("Today is Tuesday")
} else if (day_of_week === 3) {
    console.log("Today is Wednesday")
} else if (day_of_week === 4) {
    console.log("Today is Thursday")
} else if (day_of_week === 5) {
    console.log("Today is Friday")
} else {
    console.log("Today is Saturday")

Exercise: Which number is bigger?

How could we create a program that asked for two numbers and gave one of three different answers?

Hint: The start of it is…

let num1 = Number( prompt("Type a number: ") );
let num2 = Number( prompt("Type another number: ") );
if (num1 === num2) {
    console.log("The numbers are the same")

Exercise: Too hot or too cold?

Suppose you ask the user what the temperature is. Create a program that will respond as follows:

Exercise: Age calculator

I previously got you to use some Javascript date code to find the day of the week. This exercise will give you the current day, month and year so you can use it to calculate someone’s age.

let today = new Date();
let today_day = today.getDate();
let today_month = today.getMonth() + 1;  // see note below
let today_year = today.getFullYear();

let birthdate = prompt("Enter your date of birth as dd.mm.yyyy >");
let dot1_position = birthdate.indexOf("."); 
let dot2_position = birthdate.lastIndexOf(".");         // New function for you :-)
let my_day = Number( birthdate.slice(0, dot1_position ));
let my_month = Number( birthdate.slice( dot1_position + 1, dot2_position ) );
let my_year = Number( birthdate.slice( dot2_position + 1 ));

console.log("Today is ",today_day,"/",today_month,"/",today_year);
console.log("Your date of birth is ",my_day,"/",my_month,"/",my_year);

let age = today_year - my_year;
if (my_month > today_month) {
    age = age - 1;      // We haven't had our birthday yet, so subtract one
} else if (my_month === today_month && my_day > today_day) {
    age = age - 1;      // Correct month, but still haven't had our birthday yet

console.log("You are ",age," years old!");

So what is going on with the today.getMonth() + 1? It’s due to a quirk in Javascript where (for some inexplicable reason), it returns a number between 0 and 11 to represent the month, so for human purposes we always need to add one before displaying it, and then subtract one before taking a human provided value and using it to create a date object. urgh!