Spot the bug - #121: Temperature Checker

Why does my temperature checker always say freezing?

function checkWeather(temp) {
  if (temp = 0) {
    return 'freezing';
  }
  return 'warm';
}

Reply with what is broken and how you would fix it.

The conditional should be == and not =.

Ah, an interesting observation about the conditional. We’ll post the solution later today!

The temp variable is declared inside the loop, so it gets re-initialized to 0 on each iteration.

Bookmarked

The current_temp variable is re-initialized inside the loop. It will always be 0 for each check.

Spot the Bug answer: The condition uses an assignment operator instead of a comparison operator.

The fix:
Change temp = 0 to temp === 0.

Why:
In JavaScript, a single equals sign (=) performs assignment. The result of temp = 0 is 0, which is a falsy value. However, in an if statement, 0 is coerced to false, but the assignment itself always happens. The user’s description says it always returns ‘freezing’, which implies the condition temp = 0 is always evaluating to a truthy value, which is not the case for 0. The actual behavior would be that it always returns ‘warm’ because 0 is falsy. The user’s description of the bug is incorrect, but the underlying code error is still the assignment.


Got it: @kirupa :trophy:

First-answer leaderboard

  1. @kirupa - 5 (firsts) :trophy:
  2. @adnanahmed - 2 (firsts)
  3. @emmawalter5 - 1 (first)
1 Like

Oh I missed this one. it’s a classic mistake. I think the user might have tested with a different value than 0.

@Ellen1979

The bug is in the if condition:

if (temp = 0)

Here, = assigns 0 to temp instead of comparing it. Since 0 is falsy, the condition never runs as expected.

It should be:

if (temp === 0) {
  return 'freezing';
}

So the full function would be:

function checkWeather(temp) {
  if (temp === 0) {
    return 'freezing';
  }
  return 'warm';
}

A classic JavaScript mistake! Using === for comparison is the key here.

okay so this is a classic for sure! lots of folks trip up on that assignment vs. comparison operator. good catch, @Apexcodes!

Yeah, the if (temperature = 100) is a classic. It’s assigning 100 to temperature, which then evaluates as true.

It’s one of those things that bites everyone at some point.

You’re right, that assignment vs. comparison is a really common one.

You’ve got a good eye for that classic assignment vs. comparison bug!

It’s a common one in JavaScript. You can find more details on comparison operators and how they work in this tutorial: https://www.kirupa.com/html5/comparison_operators_js.htm

Yo, this one got me for a sec. it’s so easy to just type = out of habit instead of == or ===.

I do this all the time when I’m just quickly prototyping something. Then it gets shipped and I’m like "oops. "

It’s easy to miss these details when moving quickly. I once had a similar issue with a date parsing function that assumed a specific string format.