Conditions are the way in which programming languages make descisions about what to do with any given situation. This always takes the form of a test. In order to test a value JavaScript has several built in comparison operators.
Comparisons are the logic center of any programming langauge, in JavaScript they take the following forms:
Operator | Description | Example |
---|---|---|
== | Equals | age == 10 |
!= | Does not equal | weekday != "Saturday" |
< | Is less than | money < 1000 |
> | Is greater than | crowd > 40000 |
<= | Is less than or equals | passengers <= 4 |
>= | Is greater than or equals | classSize >= 10 |
Read more about comparisons on the W3Schools JavaScript comparisons page.
In order to use these comparisons operators JavaScript requires some conditional statements. There are a few of these but the most common is the if / else block.
The if statement can be used to test if a particular condition is true which is sometimes essential. Here is an example of this in use:
if (something == somethingElse) { // do something }
We can also add a condition in case we need something or something else to happen depending on the result of a given test. In this case the code would look like this:
if (something == somethingElse) { // do something } else { // do something else }
One of the other of these blocks of code will ALWAYS be executed.
The if / else block can be extended by using further conditions, such as:
if (something == somethingElse) { // do something } else if (somethingfurther == something else) { // do something else } else { // do something other }
The number of conditions to be tested can be extended almost infinitely although after a certain point (probably around your third line of else if ...) it would be much easier to use a switch / case block instead.
Here is an example of this in use:
<script language="javascript" type="text/javascript"> // declare some variables var vatRate = 0.2; var gamePrice = 10.99; // if the VAT of the game is less than £5.99 if (gamePrice * vatRate < 5.99) { // ... write a string into the page document.write("<b>You modestly paid VAT of " + (gamePrice * vatRate) + "</b>"); } else { // ... else, (if VAT is higher than £5.99) write something else document.write("VAT is frighteningly high!"); } </script>
Try this code out yourself. Try changing the value tested in the if statement to 0.50. You should see the else condition trigger as the result of the calculation and the comparision will no longer return as true.
Now open the conditionals exercise page and work through it.
You may also use the JavaScript scratch pad to try out code quickly.