I came across a small JavaScript bug that looks correct at first glance.
function isAdult(age) {
if (age = 18) {
return true;
}
return false;
}
console.log(isAdult(16));
The code prints true, even though the age is 16.
What exactly is happening here?
And would you use == or === to fix it?
I’m curious how others would explain this bug to someone who is just starting with JavaScript. Is there an easy way to remember the difference between = and ===?
The issue is = means assignment, so age = 18 changes age to 18. Since 18 is truthy, the condition returns true.
Use === for comparison:
if (age === 18)
Easy reminder: = assigns, === compares strictly.
I like that reminder. It’s like when I’m drawing, I use a light pencil for a guide line, but a dark pen for the final shape. Two different tools for different jobs.
That’s a great explanation of the assignment vs.
comparison difference.
A practical walkthrough video for this exact concept may help.
You’re right, that’s exactly what’s happening. The single equals sign assigns the value, making the condition always truthy.
For comparison, you’ll definitely want to use ===. It checks both value and type, which is usually what you need in JavaScript.
That’s a good observation about the assignment operator. I’ve seen that exact mistake lead to some truly baffling behavior in larger systems.