An if/else statement is at the core of decision-making for computers.
It's very similar to how we make decisions. If you are hungry, then you eat. If it is cold out, then you wear a heavy jacket, or if it's not, then wear a lighter jacket.
Just like decisions in life, things can get really complex if you let them. If it's cold outside, but it's not snowing, and if it's raining, then check your bicycle, and if the tires are inflated, then use it, otherwise walk.
The basic conditional to learn is the if/else statement.
Let's look at an example where we do have an else block.
If the testScore is equal to or greater than 65, then you passed, else (otherwise) you failed. Pretty straightforward?
You don't need to include the else statement. I like to show it first because it's often useful and I want you to remember it. However, you can leave it out entirely. It just means you won't have anything special happen if the condition isn't true. For example, if it's raining you want an umbrella. If it's not raining, you don't need the umbrella, so you don't even need to think about it. You can just ignore it and not do anything.
In this case, itIsRaining is a Boolean variable that is either true or false. There isn't some kind of comparison happening, like in the last example (testScores
>= 65
). The truth is, the if statement only cares about true and false. That's it. It evaluates whatever is in its
parentheses and if it ends up being true, then it carries out the first set of
commands. If not, it just moves on and doesn't do anything here.
By the way, if you have a function that returns a Boolean, you can even use that!
Remember that the function could be located anywhere else in the code, even after it is called. JavaScript finds all functions first before running any code.
Okay, it's a silly function. Calling thisIsTrue()
will always send back
true as a result. Putting it into the if statement (without the semicolon but with the
parentheses) evaluates the value that's returned. So even though it's a function, it is considered just to be a
value of true. So that alert would always pop up in this
example.
Normally you would have a function that could return either true or false. Take this example.
The function could have any number of things happening inside of it. For this, we're adding a 5 point bonus to the score (why not?). We created a new variable called passing. It compares the score to the number 65. If the score is equal to or greater than 65, then this is true, and so passing would be true. Otherwise passing would be false. We then send passing back as either true or false.
We could have simplified this function even further. Doing so reduces code, but it can make the code harder to read
and understand in some cases. Instead of the last two lines (let passing
...
and return...) we could have just used: return score
>= 65;
. It would do the same thing.