Skip to content
Science, Maths & Technology
Author:

The if...else statement

Updated Thursday 25th June 2015

Increase the power of your if statements with else.

else

Computer program Copyrighted image Icon Copyright: Dreamstime Often, you want the computer to do one thing if a condition is true and something else if the condition is false (before carrying on with the rest of the program). To do this, we use else.


Activity 1

The following is the JavaScript code from else_activity_1.html, with line numbers added for reference.

(1)  var bankBalance, withdrawalAmount;
(2)  bankBalance = 100;
(3)  withdrawalAmount = window.prompt('How much do you want to withdraw?','');
(4)  withdrawalAmount = parseFloat(withdrawalAmount);
(5)  if (withdrawalAmount > bankBalance)
(6)  {
(7)      document.write('You cannot do that!' + '<BR>');
(8)  }
(9)  else 
(10) {
(11)     bankBalance = bankBalance -withdrawalAmount;
(12) }
(13) document.write('Your bank balance is now £'+ bankBalance + '<BR>'); 
(14) document.write('Goodbye');

(a) Run the program three times, with inputs of 50, 100 and 150, and note down your outputs.

(b) What does the code on lines (5) to (12) do?

Solution

(a) An input of 50 gives the following output:

Your bank balance is now £50
Goodbye

An input of 100 gives:

Your bank balance is now £0
Goodbye

An input of 150 gives:

You cannot do that!
Your bank balance is now £100
Goodbye

(b) If the expression on line (5) evaluates to true, then the statement on line (7) (sometimes known as the if clause or if part), is executed, and the execution skips the statement in the else clause (line (11)). If the expression evaluates to false, then the if clause is skipped and the else clause is executed, so that the value of bankBalance becomes 100 minus the amount input.

In both cases, lines (13) and (14) are then executed.


The Syntax of an if...else Statement

The syntax is

if (Boolean expression)
{
    statement(s)
}
else
{

    different statement(s)
}

Note that in JavaScript this is considered to be a single language statement (an if...else statement).

The figure below provides a diagrammatic illustration of an if...else statement.

if...else statement process - execute statements before the if statement. Evaluate the boolean expression. If the result is true, execute the statements within the braces following the if. If the result is false, execute the statements within the braces following the else. After each, carry on with the rest of the program.

Activity 2

The file else_activity_2.html contains a copy of the correct code for Activity 1 (the password program).

Open the file in the text editor and modify the JavaScript source code so that if the condition (password != repeatPassword) evaluates to true, the program displays Your password is unchanged (as in the original program), but if it evaluates to false, the program displays Password successfully changed.

Test your program by entering two matching passwords and then two passwords which do not match.

Solution

Here's our code. You can also download our solution if you want to run it yourself.

var password, repeatPassword;

password = window.prompt ('Please enter your password','');
repeatPassword = window.prompt('Please re-enter your password','');
if (password != repeatPassword)
{
    document.write('Your password is unchanged' + '<BR>');
}
else
{
    document.write ('Password successfully changed' + '<BR>');
}
document.write('Thank you');


Activity 3

Now you should try writing a program like this from scratch. To get you started, here's the template we used previously.

Open the template in the text editor and write a program which asks the user whether they are having a good day today. If they enter yes, it displays the message Glad to hear it; otherwise, it displays Maybe tomorrow will be better. In either case, it finishes by saying Thank you for replying.

Hints

  • The process image above may be useful when considering the structure of your program.
  • What do you want to do before you evaluate the Boolean expression?
  • What is the Boolean expression?
  • What do you want to do if it is true, and if it is false?
  • What do you want to do afterwards?

Before you evaluate the Boolean expression, you need to ask whether the user is having a good day, and get some response. So you need to declare a variable to hold the value of the response and you need to invoke a prompt dialogue box.

  • The Boolean expression tests whether the response is yes.
  • If it is, you want to display Glad to hear it; otherwise you want to display Maybe tomorrow will be better.
  • Regardless of whether the condition is true or false you want to finish by displaying the final message Thank you for replying.

How can you test the program?

Solution

Here is our code (with line numbers for reference). As usual, your code may differ in details.

(1)  var response;
(2)  response = window.prompt('Are you having a good day today?', '');
(3)  if (response == 'Yes')
(4)  {
(5)      document.write('Glad to hear it');
(6)  }
(7)  else
(8)  {
(9)      document.write('Maybe tomorrow will be better');
(10) }
(11) document.write('<BR>' + 'Thank you for replying');

You will find a working copy of our solution in else_solution_3.html.

Your program should be tested by running it at least twice, once with the input Yes and once with some other input.

If your program did not run, or did not run as you expected, here are some common mistakes you might have made at line (3):

  • Did you use the = symbol rather than ==?
  • Did you forget to put parentheses round the Boolean expression?
  • Did you forget to put quotes round the string 'Yes'?

Note that the program expects a very specific input at line (3) – Yes. Any variation, e.g. yes or y or yeah, won't do. In Subsection 3.4, you will see how to deal with the case when you want the Boolean expression to evaluate to true in a number of different circumstances

Question: Suppose the if...else construct above is replaced by the following.

if (response == 'Yes')
{
    document.write('Glad to hear it');
}
document.write('Maybe tomorrow will be better');

How will the behaviour of the program change?

Answer

Because document.write('Maybe tomorrow will be better') is not part of the if...else construct, it will always be executed. So if the value entered is Yes, the following will be displayed:

Glad to hear it
Maybe tomorrow will be better

If the value entered is not Yes, the display resulting from these lines will be the single line:
Maybe tomorrow will be better


Activity 4

Download else_activity_4.html and complete the following if...else statement, so that the program, when run, asks the user to enter an examination mark, and then displays the message Pass if the mark is 40 or over, or Fail if the mark is under 40.

var mark;

mark = window.prompt('Please enter your mark','');
mark = parseFloat(mark);
if (add the missing code here)
{
    document.write('Pass');
}
else
{

    (add the missing code here)
}

Solution

Here's the completed if...else statement:

if (mark >= 40)
{
    document.write('Pass');
}
else
{

    document.write('Fail');
}

We'll now move onto some more complex if...else statements in the article 'Conditionals and Compound Statements'.

 

Author

Ratings

Share

Related content (tags)

Copyright information

For further information, take a look at our frequently asked questions which may give you the support you need.

Have a question?