Chapter 8: JavaScript If Statements

This Chapter

If Statements

An If Statement is used to perform an action, depending whether or not a certain Statement is true. If the Statement is true, the program does something, otherwise nothing happens. This is known as a Boolean test — the result is always true (1) or false (0).

We tend not to consciously think of using If Statements in our day-to-day lives, but we make many unconscious decisions and use assumptions to accomplish tasks. Computers are not very good at making assumptions, so you have specify exactly what you want them to do, one tiny step at a time.

Think about making a piece of toast. You subconsciously go through a series of If Statements to accomplish this:

Example 8.1

If bread bag is closed, open bread bag.
If bread is in bread bag, remove bread.
If toaster is too far away, move to toaster.
If toaster is not plugged in, plug in toaster.
If bread is not in toaster, put bread in toaster.
If toaster is not turned on, turn on toaster.
If toast is not done, wait.
If toast is done, eat toast.

We don't think about it, but those are basically the steps you must go through to make toast. That's a lot like how computer programming works.

If Statement Syntax

Create a simple If Statement to check the contents of a Variable.

First, declare a Simple Variable and give it a numerical value.

Example 8.2

var x = 5;

Now, check the contents with an If Statement:

Example 8.3

If (x == 5) {x = 6;
}

Note the difference between == and =. Two equals signs means "is equal to", whereas one equals signs assigns a new value to the variable. != means "is not equal to". The following may result in an error message:

Example 8.4

If (x = 5) {x = 6;
}

This Statement will check if the content of x is 5. If it is, x will be given a new value: 6. Otherwise, nothing will change.

What appears between the ( ) are Arguments, just like in the Methods() you looked at in the previous chapter. In this case, the program is going to check if x is equal to 5. This part of your code must always appear between parentheses. What you test can vary widely and we will discuss that further below.

{ } acts as a boundary for our code. Everything between those curly braces is code that will be executed if the condition of your If Statement is met. In this case, the code is only one line; however, it could include many lines. You must use curly braces with your If Statements, but you needn't put them on a fresh line as in the example above. Indentation in JavaScript is recommended for human readability, but it's not required as it is in some computer languages, such as Python.

The following is a perfectly valid line of code:

Example 8.5

If (x == 5) { x = 6; }

That said, your code will be much more readable if you always ensure that your Statements clearly indented as in the first example, or as in the HTML DOM examples from Chapter 4. The closing curly brace should always appear directly below the Statement that opened it. This makes it easier to know which lines of code belong with the If Statement and which do not. Always indent code so that elements which are wholly contained within another element are indented one tab (or five spaces). All examples shown here will follow this practice, and you should too.

A longer If Statement would look like this:

Example 8.6

If (x == 5) {x = 6;y = 7;z = 10;
}

Other tests you can perform

In the first example, you checked for equality (==). This is only one of many tests you can perform. Just like in grade 3 math class, you can check the following:

Example 8.7

<

Less than

<=

Less than or Equal to

>

Greater than

>=

Greater than or Equal to

!=

Not equal to

You can also create comparative Arguments using String Methods.

Example 8.8

var x = "Weather";
if (x.length > 3) {x = "Climate";
}

or you could have:

Example 8.9

if (x.match("Weath")) {x = "Climate";
}

If your XPath captured a piece of information, you could use an If Statement to check if it was something you wanted to put into Zotero. For instance, perhaps you would want to include it if it contained the word "title". If it passed the test, you could run the lines of code that will save it to the title field in Zotero. Otherwise, the program would ignore it and move on.

You can test multiple things in one Statement, or check if one of a defined list of conditions is true. To do this you use && (and) and || (or).

The following checks if x is greater than 4 AND if x is an even number.

In the first case, you know x is an even number that is greater than 4.
In the second case, you know that either x is greater than 4, or it is an even number.

Having this flexibility comes in very handy when you are attempting to write an If Statement that fulfills your specific needs.

Else/If Statement

Sometimes you will require more complex decision-making than that provided by a simple If Statement. What if you have several conditions that need to be checked? Perhaps you need to know if the String contains the substring "author" or if it contains the substring "publisher". You have two options: you could insert several If Statements in succession, or you could use an Else / If Statement.

Several If Statements in a row might work, but be aware that each Statement will be checked. This might not be desirable. For instance, what happens if multiple If Statements match and you are only looking for one match?

For example:

Example 8.12

var x = 3;

if (x < 9) {x = x + 2;
}
if (x == 5) {x = 6;
}

In this case, x will end up with a value of 6, as both If Statements will match and will therefore change x.

If you only wanted to run the first If Statement that matched, you would use an Else/If Statement.

Example 8.13

var x = 3;

If (x < 9) {x = x + 2;
} else if (x == 5) {x = 6;
}

This Statement will start checking at the first Statement (x < 9) and stop when it finds a match. In this case, the final value of x is 5.

The series must start with a properly formatted If Statement, to which unlimited Else/If Statements can be appended. The advantage of this over multiple If Statements is that it requires fewer lines of code. It also stops as soon as you've got a match. By organizing your list of Else/If carefully, you can ensure that you end up with the results you want.

Else

Sometimes you want a condition that will catch everything that didn't fit one of your other Else/If statements. This works much the same as "otherwise" works in day-to-day speech. If the toast is done, eat it. Otherwise, wait. You cannot attach a condition to an Else Statement but you can assign lines of code to be associated with it.

Example 8.15

var x = 3;

If (x < 9) {x = x + 2;
} else if (x == 5) {x = 6;
} else {x = 0;
}

or

If (x < 9) {x = x + 2;
} else {x = 6;
}

Adding Else is only useful if you want something to happen when your other conditions are not met. If you want nothing to happen if the arguments in the If Statements are not true, simply leave out the Else Statement.

Practice:

Define a Simple Variable containing a String of your choice.

Use an If Statement to check if the length of the String is less than or equal to 15.

If it is, Concatenate " My String is Short" to the end of your current String.

If it is not, Concatenate "Here is my Long String: " to the beginning of your current String.