Hacker News new | ask | show | jobs
by Raphmedia 2488 days ago
It's quite common to compare against "true" using "===" in JavaScript.
1 comments

I wouldn't say it's common. Most JavaScript developers (who aren't familiar with JS coercion rules or the difference between == and ===) wouldn't even be able to tell you for certain what the code does, exactly.

Using === to compare against "true" makes only sense if the variable can be something other than boolean (undefined, null, string etc). Or if you are programming defensively – by choice or because the codebase is messy.

> Or if you are programming defensively – by choice or because the codebase is messy.

This accurately describes the majority of JavaScript projects I have worked on.

The last web agency I worked at even had linters checking against '=='.

See this table https://dorey.github.io/JavaScript-Equality-Table/ which displays how unsure you can end up when using '=='.

> Most JavaScript developers (who aren't familiar with JS coercion rules or the difference between == and ===)

It rings strange to me that you would believe that developers who focus on one language ("JavaScript developers") wouldn't know the quirks of that language. Not all JS devs are juniors.

I prefer to follow this rule, "never use == and != unless you need type coercion". You know that your expected results is 'true' then why not test for that only?

The `in` operator always returns a boolean, though.
Maybe it was just done out of habit.

A bool can be expected today. But why about 10 years from now? Defensive programming isn't a bad thing. Making assumptions is why we had the Y2K mess.

That's an unreasonable, excessive use of defensive programming.

We're not talking about an unstable API here, we're talking about an operator.

It would be just as unreasonable to "defend" your code against `1 + 1` suddenly returning a boolean rather than a number.

You already know that ìn` will return either `true` or `false`. Why use `==` which will convert data instead of `===` which will test for a boolean directly?

Ignore the symbols and use the words. Which makes more sense to you?

"[My test] strictly equals true." or "[My test] loosely equals true."

This looks future proof to me: `if (JSON.stringify("something" in foo).match(/t/) != null) { … }`