01 / 04
The basics of syntax
INPUT · Slides
Writing the "otherwise" part
02 / 04
The shape of an else
Straight after the closing brace of the if you write else, and open another pair of braces.
Inside goes what to do when the condition did not hold.
const score = 45;if (score >= 60) { console.log("pass");} else { console.log("fail");}Result
fail
03 / 04
Exactly one of the two runs
if and else never both run, and never both get skipped. One of them always runs.
So you can stop worrying about the case where nothing gets shown.
const rain = 70;if (rain >= 50) { console.log("take an umbrella");} else { console.log("no umbrella needed");}console.log("set off");Result
take an umbrella set off
04 / 04
An else gets no condition
You put no brackets after else. Its job is to take on everything left over when the if condition failed.
That beats writing a second if with the condition turned round: it is shorter and there is less to misread. Time to write some.
const stock = 0;if (stock > 0) { console.log("in stock");} else { console.log("sold out");}Result
sold out