0

I recently read a post on reddit that said...

When you start learning JavaScript, you will likely read about never to use == but rather ===.

Which lead me to question: Is there a time when it’s makes sense to use == rather than ===?

The author replied:

If you need to do type conversion. 420 == "420" evaluates to true.

While I could see how this could be useful if comparing the value of a text input to a number easily the same could be done using toString(). Just curious what other use cases the language designers had in mind? Any good examples of using this language feature properly rather than abusing it or negative behavior?

Shane Ray
  • 1,449
  • 1
  • 13
  • 18
  • 1
    Take a look at how lodash uses it in the `isNil` function (https://github.com/lodash/lodash/blob/master/isNil.js#L20). They are coercing both `null` and `undefined` to falsy. Otherwise they'd need to check both (i.e. `value === null || value === undefined`) – lux Mar 09 '19 at 04:21
  • 2
    You’re right – it’s widely agreed on that it’s a bad idea to ever make use of `==`’s type coercion except sometimes in the idiomatic case of `== null` (which means *exactly* `=== null || === undefined`). As far as language design, well… lots of parts of JavaScript are mistakes in retrospect. – Ry- Mar 09 '19 at 04:25
  • See https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons – R. Schifini Mar 09 '19 at 04:52
  • 1
    Actually strict equality and inequality operators weren't introduced until JavaScript 1.3. They are particularly suited to testing falsey values, e.g. to differentiate between `null` and `undefined`. They are not particularly suited to testing if an object value is an object, which is usually tested for using the truthyness of the value without use of comparison operators. – traktor Mar 09 '19 at 06:06

0 Answers0