{{{{ JavaScript - Conditions }}}}

Simple if
if ... else
Multiple if ... else
Conditions
Compound if (AND and OR)
Nested if
Start of website

Alphabetical index

Summary of colours in code: green is HTML useful for JavaScript, red is JavaScript, blue is a name and everything else is grey.



Simple if

So far all the JavaScript code has been things done in order. You need something more complicated in order to write a program - you need conditions. That is, sometimes you do one thing, sometimes you do another, and choosing which to do needs an if statement. The example below uses a simple if. It is checking if a date entered is (roughly) OK. First it checks if the input day number is greater than 31 (> means greater than). If it is then you get an alert box. We've already met return with a variable. The return (by itself, without a variable) means "leave the function now without doing any more processing." You need that here, or it would do both the first and the last alert box. The second if statement checks the month number. Since both return statements are within the if statements, if you manage to get past both of them, then both the day and month number must have passed the check, and so the date is OK. I say so with an alert box, but in a real program, I would imagine you'd use the date somehow.

Note the format of the if statement - it is quite complicated. You have if, then the condition in round brackets, then what you want done if that condition is true in curly brackets. I have formatted it with spaces (rather like a function statement), but that is entirely for you and me to be able to read it easier. The computer doesn't understand formatting, and the if statement would still work if there were no spaces at all (but please don't! Formatting is extremely helpful to understanding the program. You can choose your own formatting style, but please make it easy to understand). The computer works entirely by brackets - you might say it gets obsessed by them! Remember, every open bracket requires a closed bracket of the same type, and types are very important. The condition goes inside round brackets, and the code for what to do does in curly ones. In fact, I used to find if statements almost impossible to type, and kept getting the wrong type of bracket, or missing the end brackets. Now, I always start typing an if statement like this "if () {}", then move the cursor back to type in the contents of the brackets. That way, at least I can guarantee that I haven't missed out a bracket!

Enter day and month
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Check dates

function check() {
  if (document.date.day.value > 31) {
    alert ("Day number too large")
    return
  }
  if (document.date.month.value > 12) {
    alert ("Month number too large")
    return
  }
  alert ("Date is OK")
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME=date>
Enter day and month<BR>
<INPUT TYPE=TEXT NAME=day SIZE=2>
<INPUT TYPE=TEXT NAME=month SIZE=2>
<INPUT TYPE=BUTTON VALUE="Check date" ONCLICK="check()">
</FORM>
</BODY>
</HTML>

Alert thinkers may realise that this is not a very good date check. It would allow 30th February, for example. I think that a better date check would use a Select box with the month names in, with values of the maximum valid days in each month, which you could test very easily. But even that wouldn't cope with February and leap years. Checking dates is horrid, basically! But this example does demonstrate a simple if statement.



if ... else

Often you need to do one action if a condition is true, and another if it is false. The example below shows how to do this, using if ... else. You enter two numbers into the input text boxes, and click on the button. The function "order" puts these two values into "in1" and "in2". Then the if statement checks to see if "in1" is less than "in2" (that's what < means) and if they are, it puts "in1" into "out1" and "in2" into "out1". If they're aren't, it puts "in2" into "out1" and "in1" into "out2" Then (in both cases) the output text box values get set up.

The if and the else are all one statement - you can't have an else without an if. You can also see that else has curly brackets round what you do, but it has no round brackets, because it doesn't have a condition of its own, it just has the opposite of whatever the if is. You can see that the bracket situation is beginning to look complicated, so make sure you format the code properly so you can spot missing brackets!

I have used parseFloat(). This makes sure than the variables are treated as numbers. I didn't, to start with, and while it said that 54 was greater than 45, it said that 54 was smaller than 9! It was treating the input as strings, and that is how strings are ordered.

Enter two numbers




<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Put input numbers into order

function order() {
  in1 = parseFloat(document.ord.ina.value)
  in2 = parseFloat(document.ord.inb.value)
  if (in1 < in2) {
    out1 = in1
    out2 = in2
  }
  else {
    out1 = in2
    out2 = in1
  }
  document.ord.outa.value = out1
  document.ord.outb.value = out2
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME=ord>
Enter two numbers<BR><BR>
<INPUT TYPE=TEXT NAME=ina SIZE=5>
<INPUT TYPE=TEXT NAME=inb SIZE=5>
<BR><BR>
<INPUT TYPE=BUTTON VALUE="Output in order" ONCLICK="order()">
<BR><BR>
<INPUT TYPE=TEXT NAME=outa SIZE=5 DISABLED>
<INPUT TYPE=TEXT NAME=outb SIZE=5 DISABLED>
</FORM>
</BODY>
</HTML>




Multiple if ... else

You may want to test a number of conditions. This is especially true of Select statements. Here, I have used a SELECT and dynamic HTML to change the colour of text. (The example page gives you a choice of more colours.) Once you select a colour, the function "change()" is run. This tests the VALUE selected. It would be possible to test the SelectedIndex instead, but I advise that you set up and test VALUE. If you ever change the SELECT by adding a line in the middle, then the whole SelectedIndex is out by one, and you need to change a lot of program! Also VALUE makes the program easier to understand. The test this time is equals, or ==. That is a double equals. A single equals will not work! A single equals means set one thing equal to another, and here we are testing two things against each other, which is entirely different. So double equals, it is. (And this will probably be another frequent mistake that you will make, especially if you are used to programming in a different language!) Finally the changed HTML is set up. If you don't understand this, then this website on HTML explains it.

*** Hello World! ***
<HTML>
<HEAD>
<SCRIPT TYPE="TEXT/JAVASCRIPT">

// Make text different colours

function change() {
   var str = ""
   if (document.col.shade.value == "red")
      {str = "FF0000"}
   else if (document.col.shade.value == "green")
      {str = "00FF00"}
   else if (document.col.shade.value == "blue")
      {str = "0000FF"}
  document.getElementById('fontcol').innerHTML="<FONT COLOR='#" + str + "'>*** Hello World! ***<" + "/FONT>"
}
</SCRIPT>

</HEAD>
<BODY>
<FORM ACTION="#" NAME=col>
<SELECT NAME="shade" ONCHANGE="change()">
<OPTION VALUE="red">red</OPTION>
<OPTION VALUE="green">green</OPTION>
<OPTION VALUE="blue">blue</OPTION>
</SELECT>
</FORM>

<SPAN ID="fontcol">
<FONT COLOR="#FF0000">*** Hello World! ***</FONT>
</SPAN>
</BODY>
</HTML>

You can see that I have laid out the code in a different way in this example. In the previous example, else had curly brackets round what it did. In fact, if curly brackets only have one statement, then you can leave them out, and else if does contain a single statement. You could put them in, and format the code as in the previous statement, but this would leave lots of close curly brackets at the end of the entire if statement (and would you remember them all?) What is more, each if statement would require you to put a few more spaces in front of its contents, so the code would gradually march across the page! Another method would be multiple if statements. After all, only one will be actioned. There are two reasons why I don't like this. First it means that you will have to check every if statement every time you call the function, even if the first one was true. With a multiple if ... else, if the first if is true, then it ignores the else (which contains all the other if statements), so you action less statements. Of course, in this case, that doesn't matter much. Computers are so fast nowadays that a few statements actioned when they don't need to won't slow things down! But those of us who remember the days when even large computers memory was measured in kilobytes prefer not to. More to the point, if you get used to using multiple if statements rather than if ... else, you will eventually met a program where the contents of the if statement alter the variables in the condition. That will make you action a later if statement when you didn't mean to. Another technique, which I used in the first example on this page, is to return out of the function at the end of every if statement. That will only work if that is what you want to do. You might have some statements which you want to action at the end of the if statements, for all possible conditions. So all-in-all, I prefer my if ... else statements, laid out as above! But this decision is a personal one, and other programmers may disagree. If you don't understand any of this argument, go away and write programs for a few years, find lots of bugs, and then come back and read this!

By the way, if you're wondering why I broke up the literal in the dynamic HTML, it was to make it conform to standards. The standards checker objected when I used </FONT> in the literal!



Conditions

In the examples above, I have used several conditions, such as less than, equals and greater than. Here is a table of conditions:

ConditionJavaScripta contains
357
equalsif (a == 5) {...}FalseTrueFalse
less thanif (a < 5) {...}TrueFalseFalse
greater thanif (a > 5) {...}FalseFalseTrue
not equalsif (a != 5) {...}TrueFalseTrue
less thanif (a <= 5) {...}TrueTrueFalse
greater thanif (a >= 5) {...}FalseTrueTrue

So you have two symbols in the condition apart from less than and greater than. The first symbol in the "not equals" is an exclamation mark. Don't forget the double equals for "equals". And please don't forget the brackets.



Compound if (AND and OR)

In this example, new Date().getHours() gets the current hour of day.

The first if statement is easy enough - if the hour is less than or equal to 6 (that is, before 6am), then it must be night-time. The next if statement has two bits in the condition, with && between them. This means AND. So the statement means "if the hour is greater than 6 and less than or equal 12 then it must be morning". We need AND rather than OR, because "if the hour is greater then 6 or less than or equal to 12" would cover every possible hour! And so on, for the rest of the day. (I could have used else, but I couldn't be bothered.) You must use the double ampersand for AND - & by itself won't work. By the way, note that I have been careful with the conditions to cover the whole range. If I had just used < and >, then 6am wouldn't pass any condition.

Then I write HTML directly to the webpage.

The next two if statements check if the greeting is for morning or afternoon, where || means OR. That symbol is double vertical bar, by the way (bottom left of the keyboard). Again, you must have two of them.

<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
var hour=new Date().getHours()
var greet=""
if (hour<=6) {greet="Good night!"}
if (hour>6 && hour<=12) {greet="Good morning!"}
if (hour>12 && hour<=18) {greet="Good afternoon!"}
if (hour>18 && hour<=24) {greet="Good evening!"}
document.write (greet)
document.write ("<BR><BR>")
if (greet=="Good morning!" || greet=="Good afternoon!") {document.write ("It's day-time!")}
if (greet=="Good evening!" || greet=="Good night!") {document.write ("It's night-time!")}
</SCRIPT>

</BODY>
</HTML>
If you're not sure whether to use AND or OR, one quick check is that OR generally gives you more 'hits' than either of the conditions by themselves, while AND gives you less. So that (hour>6 && hour<=12) is true less often than (hour>6), which would be true anytime after 6am. But (greet=="Good morning!" || greet=="Good afternoon!") covers more than just the morning, it covers the afternoon as well.

I should add that || is an inclusive OR, that is, it's true if either conditions are true and if both conditions are true. This is slightly different from normal English. We tend to say "If this is true, or that is true, or both ...". Since we add "or both", we are implying that English OR doesn't usually include both. JavaScript OR does include both as well as either.



Nested if

Some people find Boolean conditions (AND, OR) very simple, other people don't. In fact, it is possible to avoid using them altogether. You can replace OR with several if statements, one after the other, possibly with else used as well. You will have to repeat the code (but you could make it into a function if this gets to be a problem). You can replace AND with nested if statements, that is, one if statement inside another one. I have rewritten the example above to show both these.

<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
var hour=new Date().getHours()
var greet=""
if (hour<=6) {greet="Good night!"}
if (hour>6) {
   if (hour<=12) {greet="Good morning!"}
}
if (hour>12) {
   if (hour<=18) {greet="Good afternoon!"}
}
if (hour>18) {
   if (hour<=24) {greet="Good evening!"}
}
document.write (greet)
document.write ("<BR><BR>")
if (greet=="Good morning!") {document.write ("It's day-time!")}
if (greet=="Good afternoon!") {document.write ("It's day-time!")}
if (greet=="Good evening!" ) {document.write ("It's night-time!")}
if (greet=="Good night!") {document.write ("It's night-time!")}
</SCRIPT>

</BODY>
</HTML>

On the other hand, you may find that harder to understand than the previous example. Whether you use compound if statements or nested if statements is up to you. It's a matter of personal programming style. Code the way you understand, and you'll find it a lot easier to make it work. You may well find that you sometimes use one way and sometimes another. However, if you do use nested if statements, you will rapidly find brackets all over the place. In the example above, there are 2 pairs of brackets for each nested if. It is conventional to put some spaces in front of each if, and for nested if stataments, then put more speces for the inner if. This will help you sort it out in your own mind. However, do remember that the computer ignores all this pretty spacing. It concentrates on the brackets alone. So miss a bracket out and you will confuse the computer badly.





Return to JavaScript index



Valid HTML 4.01!

© Jo Edkins 2005