As we have seen, everything in JavaScript will be either true
or false
, we can use this to direct the flow of our application.
if (something is true) {
// Do thing
}
In the above example, the thing will only be executed if something
is truthy. If it is falsey it will skip that part of the code.
When determining if something
is truthy, let's look at some operators we can use:
OPERATOR | EXPLAINATION |
---|---|
=== | Is equal to |
!== | Is not equal to |
>= | Is greater than or equal to |
> | Is greater than |
<= | Is less than or equal to |
< | Is less than |
Let's look at a real example.
let balance = 100
if (balance <= 0) {
// Do something when a users balance is negative
} else if (balance === 0) {
// Do something if the balance is 0
} else {
// Do something if the balance is positive
}
When we use these conditional operators, we do not test if the value of balance
itself is truthy or falsey, but instead if the result of balance
when run on these operators is truthy or falsey.
E.g When balance
is 0, balance
is falsey, but balance === 0
is truthy
The three keywords here are:
if
else if
else
You can simply just have an if
block and nothing else, you can also have if...else
with no else if
.
If you just use if
on its own, be aware that when it is true and the block inside the if
condition is run, when there is no else
it will carry on at the same point as a condition where it was false.
For example you would want to avoid the following:
if(balance < 0) {
console.log('You have a NEGATIVE balance!!);
}
console.log('You have a POSITIVE balance');
In this example, if the balance was less than 0, then BOTH console logs would be printed.