If statements allow us to conditionally run code. We do this because we may want to run different code and chose between two blocks of code base on some predetermined values.
Think of conditionals in the same way you’d get a conditional acceptance for a job offer that requires you to send over a reference.
If you have a reference, then you get the job. We can write this out in code like this.
var hasReference = true;
if(hasReference) {
console.log("You got the job");
}
We also want to say something when we don’t have enough references. In this case we can use an else statement.
If we have a reference, you got the job, otherwise (or, else) you didnt get the job
var hasReference = true;
if(hasReference) {
console.log("You got the job");
} else {
console.log("You didn't get the job");
}
What if we don’t have a reference, but we impressed our interviewers so much that they’ll give us a job even if we don’t have a reference. They’re so confident in us, that we want to add another conditional in case we didn’t have a reference, but we did so well on the job interview that we don’t need one.
Basically, if we have a reference, we get the job, if we don’t have a reference but we nailed the interview, we also get the job. If we don’t have a reference and we didn’t get the interview, we don’t get the job.
var hasReference = false;
var nailedTheInterview = true;
if(hasReference) {
console.log("You got the job");
} else if(nailedTheInterview) {
console.log("You don't have a reference but still got the job");
} else {
console.log("You didn't get the job");
}
Note that if we already have a reference, our else if statement will never be reached because we’ve already satisfied the condition of our if statement. Only if the conditional in our if statement is false will we reach our else if statement