JavaScript Problem: Why Does This Return the Wrong Result?

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.

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.

It’s so easy to make that mistake. I remember one time I spent hours debugging a CSS issue that was just a missing semicolon. :woman_facepalming:

That’s the kind of thing that makes you question your career choices at 3 AM.

I’ve seen similar issues with content migrations where a small character error in a template can cascade into hundreds of broken pages. It’s a reminder that precision in syntax is critical, even for seemingly minor details.