You can do it that way too! The else if
syntax can be considered syntax sugar (something that is done to help make the code cleaner, but doesn’t add any new functionality not previously available) . You can write your code without ever using else if, as there a number of alternavies. (I will only go into a few below) You could easily just used normal if
, and else
this way:
if (age < 4) {
return “You are too young for Lego”;
} else {
if (age > 99) {
return “You are too old for Lego”;
} else { // they are between 4 and 99
return “Go play with Lego!”
}
}
As you can see, this a lot more verbose, and not flat. If you added more cases you would end up with very “nested” code inside of each other. This is something you generally want to prevent. Written code “scales” better vertically than horizontally, if you ever find yourself scrolling left to right to read code, odds are things are not written with the reader in mind. (IE it’s badly structured code) It may work the same, but the computer doesn’t care about how it looks, only people and since people will be reading the code more often than writing it, its important to write the code with readers in mind.
Also this line: } if (age >99) {
is not common practice, as it’s too easy for the reader to “skip over” the if statement after the bracket. Its best to leave it on its own line.
Finally, I’d like to mention my personal approach of just not using else alltogether
If your inside of a function, you can prevent the execution of the rest of the function alltogether using return
, as once return is called, the rest of the code in the function is skipped.
function getLegoMessage() {
if (age < 4) {
return "You are too young for Lego";
}
if (age > 99) {
return "You are too old for Lego";
}
// NOTE: this line is executed only if the previous 2 if statements aren't executed.
return "Go play with Lego!"
}
PS. Finally if you wanted to be as concise as possible, you could use a well formatted nested ternary. But I would only recommend this if you format it and can understand the syntax well enough:
function getLogoMessage() {
return age < 4
? "You are too young for Lego"
: age > 99
? "You are too old for Lego"
: "Go play with Lego!"
}