The basics of syntax

INPUT · Slides

Writing the "otherwise" part

01 / 04

You want to do something in the other case too

With only an if you can say what happens when a condition holds. A pass gets announced, but nothing at all comes out for a fail.

else is where you write "otherwise, do this".

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