Paul Baumgarten

Computer Scientist, teacher, freelance programmer and self confessed geek

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: * The parenthesis ( and ) are used to enclose the query we are wanting Javascript to run. * The curly braces { and } are used to denote which commands should be executed as a result of the condition being true. * The intendation is not a "mandatory" requirement of Javascript, but is for me (ie: if you are a student of mine wanting a good mark!). Intendation is used by programmers to visually organise their code into logical blocks. It makes programming code a lot easier to maintain and is a very good habbit to get into.

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:

  • If the sisters age is greater than the brothers age, print "Sister is older" then skip the rest of the "if" stuff
  • Otherwise, if the sister age is the same as the brothers age, print "Ages are the same" and then skip the rest of the "if" stuff.
  • Otherwise, if nothing has been true yet, print "Brother is older"

The general rule is:

if (comparison_is_true) {
    do_something;
} else if (alternative_comparison_is_true) {
    do_this_instead;
} else {
    do_this_if_nothing_has_been_true;
}
carry_on_with_other_stuff;

Important notes:

  • The "do_something" bits can be one line or 100 lines of code.
  • You can have an "if" inside an "if" inside an "if" etc!
  • You can have as many "else if" blocks as you like
  • Please keep the level of indentation consistent throughout!

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?

  • The first number is bigger
  • The second number is bigger
  • The numbers are the same

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: * If the temperature is between 20 and 27, say that it is "Just right" * If the temperature is below 20, say that it is "too cold" * If the temperature is above 27, say that it is "too hot"


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.

  • Can you get it to work?
  • Can you add code to wish the user a Happy Birthday if it is their birthday?
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!