You have now learned how to write conditional statements. Now we'll talk a little bit more about how to write them using best practices.
When you finish this reading, you should be able to:
Say you are given the challenge to write a function that will call another function named bigNumber if the given argument is greater than 100 or call a function named smallNumber if the given argument is smaller. You could write a function to do that which would look like this:
function numberSeparator(number) {
if (number < 100) {
// number is smaller than 100 so invoke smallNumber
smallNumber();
}
if (number === 100) {
// number is equal to 100 so invoke smallNumber
smallNumber();
}
if (number > 100) {
// number is larger than 100 so invoke bigNumber
bigNumber();
}
}
As you can probably tell the above function uses a lot of code to do a simple task. To be clear the function above would work for our aim - but it repeats itself. There is an age old principal for writing good code named DRY or Don't repeat yourself. As good programmers we always want our code to be clear, concise, and efficient.
A general rule of thumb is that if you are working with a condition that is mutually exclusive, meaning if one condition is true the other condition must be false, then you should use an if/else statement. You can also think of mutual exclusivity like a coin flip - it can be either heads or tails but not both.
Going back to the original problem at hand you can see it makes intuitive sense with the way the challenge is phrased: If the number is larger than 100 then you'll call bigNumber, otherwise you invoke smallNumber.
So let's rewrite the above function to read a little more clearly:
function numberSeparator(number) {
if (number > 100) {
bigNumber();
} else {
smallNumber();
}
}
// this also works
function numberSeparator(number) {
if (number <= 100) {
smallNumber();
} else {
bigNumber();
}
}
Look at how much clearer that is! Writing good code is an art - devote yourself to becoming an artist!