MSc-IT Study Material
June 2010 Edition

Computer Science Department, University of Cape Town

Conditional Execution

As in Java, JavaScript provides an if statement which, based on the value of a variable or other expression, can conditionally choose particular JavaScript code to execute.

JavaScript if statement

The if statement appears exactly as it does in Java (an expression that evaluates to true or false must be included in parentheses):

    if (true or false expression)
    statement
      

The expression in parentheses is evaluated and if it is true the following statement is executed; if it is false, it is not.

Recall that the window.confirm() method returns true or false depending on whether the user clicks OK or Cancel. We will now use confirm() in an example of the if statement:

    <SCRIPT>
    var member
    member = window.confirm('Please confirm you are a member of the shopping club')
    if (member)
    window.alert('Welcome to the Shopping Club')
    </SCRIPT>
      

This code produces a confirmation dialogue box. When the user clicks OK a welcome dialogue box appears, as below.

if statements also have a matching else statement, which behaves as in Java:

    if (true or false expression)
      statement_1
    else
      statement_2
      

statement_2 is only executed if the expression in parentheses evaluates to false.

Exercise 7

Change the previous script to display the following dialogue box if Cancel is clicked by the user when asked to confirm membership.

You can find a discussion of this exercise at the end of the unit.