JavaScript If Statement
Often you will want to only do something if a certain condition is true. For example, you may only want to redirect the user to a new page if they have not been to your site before. We use the JavaScript if condition statement for this.
var somenum = 10;
if (somenum == 10) {
somenum = 20;
}
Similar to a function declaration, an if block starts with the keyword, has the parameter in parenthesis, and the associated code within curly braces ({ and }).
Conditions
The code within the if block is only executed if the condition is true. Here are some sample conditions:
if (variable == "a word") |
Is variable equal to the string "a word"? |
if (variable > 10) |
Is variable greater than 10? |
if (variable <= 20) |
Is variable less than or equal to 20? |
if (variable != true) |
Is variable not equal to true (i.e. false)? |
if (myFunction() == true) |
Is the return value of myFunction() equal to true? |
if (myFunction()) |
Same as above, == true is assumed. |
Remember, when checking for equality with ==, you must use two equal signs! One equal sign has a different meaning - it means you assign the value to the variable (yes, within the if statement!). A single equal sign will produce unexpected results, so always use two equal signs.
Else and elseif
Now, often you want to do something if the condition is true, or something else if the condition is false. This is where else comes in. An else is basically the opposite of the if and serves as a second block of code, like so:
x = true;
if (x == true) {
document.write('x is true!');
} else {
document.write('x is not true!');
}
There is no condition section after the else; it is simply executed if the opposite of the if
condition is true. Only one of the code blocks will ever get executed -
in this example, the script will never write out both "x is true!" and
"x is not true!".
Also, notice we indented the code within the if block. This
is good practice and helps you see at a glance which code is within the if block and which isn't. Typically, whenever you open a curly brace,
all the code following until the next curly brace is intended. You can
indent with a tab or 4 spaces.
However, what if you want to check one or more similar conditions? That's where elseif comes in.
x = 12;
if (x < 10) {
...
} elseif (x > 20) {
...
} else {
...
}
Here, we first do something if x is less than 10, something else if it's greater than 20, and finally something else if neither are true (i.e. if it's in between). An else is not compulsory for an elseif, nor is an elseif compulsory for an else. You can have as many elseif's as you like, but only one else.
Next, let's take a look at the JavaScript while loop.
| « JavaScript Functions | JavaScript While Loop » |

