VCF

Unit 4 · Thinking like a programmer

== vs === in JavaScript: which to use

Use ===. == converts types for you before comparing, and its rules surprise people. If the types differ, convert on purpose, for example Number(answer) === 7, so the conversion is visible in the code.

The mix-up

What people often think

“Switching to == is the clean fix.”

What the tutor says

== converts types for you behind the scenes, and its rules surprise people. Convert on purpose with Number() and keep ===.

How it works

"7" == 7 is true and "7" === 7 is false. Switching to == can make a quiz check pass, but it hides the real issue: the answer arrived as text.

Changing the test data to a number only fixes that one case. The input box will always send text, so convert in the check itself.

Side by side

The mix-upJavaScript
if (answer == 7) { ... }  // works by accident
A hidden conversion.
What worksJavaScript
if (Number(answer) === 7) { ... }
Convert on purpose, compare strictly.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “Changing "7" to 7 at the top fixes the quiz.”

    That only fixes this one player. The answer box always sends text, so convert it in the check.

Practise it with a tutor watching

Types: text, numbers and yes/no

Tell strings, numbers, booleans and null apart, and convert text to numbers on purpose.

15 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.