01 / 04
The basics of syntax
INPUT · Slides
Splitting three ways or more
02 / 04
The shape of an else if
Between the if and the else you slot in else if (condition) { }. Put in as many as you like.
The final else still does the same job: it takes whatever matched none of them.
const score = 75;if (score >= 90) { console.log("excellent");} else if (score >= 60) { console.log("pass");} else { console.log("try again");}Result
pass
03 / 04
Tried from the top, stops at the first hit
The conditions are tried from the top, and only the first one that holds runs. Nothing below it is even looked at.
So get the order wrong and you end up in the wrong branch. Below, a 95 gets stuck on pass.
const score = 95;if (score >= 60) { console.log("pass");} else if (score >= 90) { console.log("excellent");} else { console.log("try again");}Result
pass
04 / 04
Put the strictest first
When you split by range, the trick is to put the narrowest, strictest one first. Picture it as a series of sieves.
The else may be left out. Leave it out and nothing happens when nothing matches. Time to write some.
const temp = 5;if (temp >= 30) { console.log("hot");} else if (temp >= 20) { console.log("pleasant");} else if (temp >= 10) { console.log("cool");} else { console.log("cold");}Result
cold