JavaScript Making Decisions

Information entered into a form may need different validation depending on where your visitor lives or whether they are male or female. An object being moved around the page needs to change direction when it reaches the edge of the browser window. The background displayed behind part of our page may be different depending on when the page is displayed.

All of these actions require that the JavaScript make a decision as to which of several different tasks to perform. JavaScript makes decisions by testing a Boolean value in order to see whether that value is true or false. An appropriate action is then performed depending on whether it is true or not.

Most of the variables that we work with are not Boolean. We convert other variable types into Boolean values by performing comparisons. We can compare two values to test if they are equal. When they are equal then the comparison returns true and when they are not equal then the comparison returns false. If we compare two numbers to see if one is greater than the other then if it is greater then the comparison returns true and if it not greater then the comparison returns false.

JavaScript uses comparison operators to compare two numbers, text strings or other data types to return a Boolean result of true or false.

Once we have a Boolean value (either from a Boolean variable or returned from a comparison) we can then test that value to decide what code to run next. JavaScript performs this test using an if statement. We can have the JavaScript perform any number of completely different tasks based on the decisions that it makes by performing these tests.

In this series of tutorials we will explore the different ways that JavaScript provides for performing comparisons and performing tests in order to decide what code to run.

go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow