JavaScript Making Decisions

The ELSE Clause

We could add code to be run when the condition in our if statement is false by adding a second if statement that tests the opposite condition. This would be inefficient as it means that we have to test the same condition twice.

JavaScript provides a way of adding a statement or block of statements to our if statement that will be run when the condition is false. We do this by adding an else clause to the end of our if statement. This means that we only have to test the condition once in order to decide which of the two blocks of code to run.

if ('Stephen' === name) {
    message = "Welcome back Stephen";
} else {
    message = "Welcome " + name;

We now have code where one of the two blocks of code contained within the braces will always be run. Which of the two blocks that actually does run depends on whether the condition that the if statement tests is true or false. When the condition is true the first block of code runs and when it is false the second block of code runs. In our example if name is a text string with a value of "Stephen" then "Welcome back Stephen" is assigned to message. If name has any other value then the alternative welcome message is set.

go to previous section go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow