The conditonal if
statement is very important in JS and has many uses.
The basic syntax is:
if (num > 7) alert('too high');
Its more usual to wrap the code in curly braces and you have to if there is more than one statement to execute:
if (some condition) {
// do this
}
You can also use else
within an if
block to do something if the first block turns out to be false
.
if (some condition) {
// do this
} else {
// do that
}
Finally if checking for multiple conditions and outcomes you can use else if
with another condition.
if (num > 1000 ) {
alert('warning: too high');
} else if (num > 1500) {
alert('Danger stop now');
}
Operators
This is often used with the equals and or operators: ===
and ||
.
There is also not equal, *and, less than, greater than, less than or equal to and greater than or equal to:
Operator | What it does |
---|---|
!== |
Does not equal (type sensitive) |
!= |
Does not equal (type insensitive) |
&& |
and |
< |
less than |
> |
greater than |
<= |
less than or equal to |
>= |
greater than or equal to |
if (pettyCash <= 50) {
alert("We need more cash!");
}
Nested if’s
You can also nest if statement inside one another if you want several conditions to be met. This can be clearer if there are many different conditions:
if (weather === "rain") {
if (forecast === "bad") {
if (money < 20) {
alert("Do not go");
}
}
}
The Ternary operator
This is a short way of writing if / else statement.
In an if / else statment there are 3 parts:
- The condition to be met
- What to do if true
- What to do if not true
These three parts can be split with the ?
and the :
the condition ? when true : when false
So this:
if (pettyCash <= 50) {
alert("We need more cash!");
}
else {
alert("We have enough money now");
}
can be written as
pettyCash <= 50 ? alert("We need more cash!") : alert("We have enough money now");