The basics of syntax

INPUT · Slides

Checking whether two things are the same

01 / 06

You often want to ask "is it the same"

Bigger and smaller is not everything. Plenty of the time you want to know whether something is exactly the same. Is the password right? Is the chosen colour red?

For that you use ===. The trick is that you write three equals signs.

console.log(5 === 5);console.log(5 === 8);

Result

true
false

02 / 06

One equals sign means assign

Write a single = and it means "put the thing on the right into the thing on the left". You meant to compare and instead you overwrote something — a classic accident.

  • = … put in (assign)
  • === … ask whether they are the same (compare)

They look alike, so keep it in mind as you type.

03 / 06

Strings can be compared too

=== works on strings as well as numbers. One character out and you get false.

const color = "red";console.log(color === "red");console.log(color === "blue");

Result

true
false

04 / 06

Not the same is !==

To ask whether they differ, use !==. Picture it as the result of === turned upside down.

It goes straight into an if just the same. Time to write some.

const command = "forward";console.log(command !== "stop");if (command === "forward") {  console.log("one step forward");}

Result

true
one step forward

05 / 06

Watch out for == with two equals signs

JavaScript also has ==, a comparison with two equals signs. It compares loosely, converting types before checking.

"5" == 5 converts the string "5" to a number first, so it comes out true — two different types matching each other.

console.log("5" == 5);console.log("5" === 5);console.log(0 == false);

Result

true
false
true

06 / 06

Stick to === as your default

Make ===, which checks the type too, your default. == lets things through as long as the contents are close enough even when the types differ, which is a common source of unexpected bugs.

Real-world code barely uses == at all. Knowing === and !== is enough.