Unit 4 · Thinking like a programmer
= vs === in JavaScript
A single = assigns: it copies the value on the right into the variable on the left. === compares: it asks whether two values are the same and answers true or false.
The mix-up
What people often think
“One = inside an if checks whether two things match.”
What the tutor says
One = copies password into attempt, and a non-empty text counts as true, so the if always runs. Use === to compare.
What does attempt hold after the if line runs?
How it works
Write if (attempt = password) and the if does not compare anything. It copies the password into attempt, and because a non-empty string counts as true, the if always runs. The check also overwrote what the person typed.
Read = as “becomes” and === as “is it equal to?”. Inside an if, you almost always want the question.
Side by side
if (attempt = password) {
unlock();
}if (attempt === password) {
unlock();
}Close cousins of this mix-up
The tutor watches for these in the same lesson.
“score === 5 puts 5 into a box.”
Three equals signs ask a question: is score 5? The answer, true or false, is what goes into isFive.
“An if only reads the values, so it cannot change them.”
This one wrote over attempt. After the line runs, attempt holds the password, not what the person typed.
Practise it with a tutor watching
Variables are labelled boxes
Store values in variables, update them, and tell assigning apart from comparing.
Free, no account needed.