The basics of syntax

INPUT · Slides

Doing something only if

01 / 05

Always doing the same thing is not enough

Everything you have written so far runs all the way through, every time.

But a real program nearly always wants to do something different depending on the situation — "say pass if the score was high enough", that sort of thing.

02 / 05

The shape of an if

In the brackets after if goes the condition, and inside the curly braces {} goes what to do when it holds.

score > 60 means "score is greater than 60". Same symbol as in your maths book.

const score = 80;if (score > 60) {  console.log("pass");}

Result

pass

03 / 05

What is inside the braces is one chunk

The part wrapped in {} is called a block. When the condition holds, everything in the block runs, top to bottom.

The contents are shifted two spaces to the right. That is called indentation, and it is a habit that makes it easy to see where a block starts and stops.

const rest = 3;if (rest < 5) {  console.log("running low");  console.log("time to restock");}console.log("check done");

Result

running low
time to restock
check done

04 / 05

If it does not hold, the block is skipped

When the condition does not hold, the whole block is skipped. It is not an error — it just quietly walks past.

Only the block is skipped. Lines below the } run as usual.

const temp = 18;if (temp > 30) {  console.log("hot");}console.log("done");

Result

done

05 / 05

Four symbols for comparing

Learn the symbols that turn up in conditions before you start.

  • a > b … a is greater than b
  • a < b … a is less than b
  • a >= b … a is b or more (equal counts)
  • a <= b … a is b or less (equal counts)

You choose between > and >= by whether exactly equal should count. Time to write some.

const point = 100;if (point >= 100) {  console.log("you get a gift");}

Result

you get a gift