Equality: Why === Beats ==

Grade 3, page 6 of 11. A one-minute read.

Here's a big one. JavaScript has two ways to check if things are equal:

  • === is strict equality. It checks that both the value and the type are the same.
  • == is loose equality. It converts the values to the same type first (using that sneaky type coercion from Grade 2), and then compares.

And there are two matching "not equal" operators: !== (strict) and != (loose).

Watch what happens:

JavaScript
console.log(5 === 5);
console.log(5 === "5");
console.log(5 == "5");
console.log(0 == false);
console.log("" == 0);
console.log(null == undefined);
console.log(null === undefined);

It prints

true
false
true
true
true
true
false

With ==, JavaScript thinks the number 5 equals the string "5", that 0 equals false, and that an empty string equals zero. These loose conversions follow a long list of complicated rules that almost nobody remembers.

Watch outAlways use === and !==

The loose == operator causes so many bugs that most developers simply never use it. Always use === and !==. They do exactly what you'd expect: two things are equal only if they're the same type and the same value. No surprises, no coercion, no Buggsy.

Watch outDon't mix up = and ===

= assigns a value (put into the box). === compares values (are they the same?). Writing = when you mean === is one of the most common beginner mistakes. One equals sign is an action; three equals signs is a question.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning