-2

Which of the following lines is correct?...

if (typeof value == 'boolean') { return value; }

... or ...

if (typeof value === 'boolean') { return value; }

I thought the double equal sign was a type of "soft compare" so the value variable could either be a string or formal type. Is this not so? I wonder because JSHint complained about the first version. I've changed it but now I'm worried that typeof won't return a string.

G. Deward
  • 1,542
  • 3
  • 17
  • 30
  • 1
    `typeof` will always be consistent. When in doubt read the docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – charlietfl May 28 '16 at 17:24
  • 1
    Both are "correct", but `===` is generally preferred because it's almost always the expected behaviour. – Daniel Diekmeier May 28 '16 at 17:26
  • So, does this mean there are not types in JS? If so, then why would `typeof` return a string instead of a `type`. – G. Deward May 28 '16 at 17:27
  • Again...read the docs to answer last comment – charlietfl May 28 '16 at 17:28
  • Many consider `==` and `!=` to be bad practice, and always use the strict versions `===` and `!==` even when the type is known to be the same. Being consistent is also probably *slightly* better for GZIP. – Alexander O'Mara May 28 '16 at 17:28
  • @G.Deward _"why would typeof return a string instead of a type."_ Because it's designed to return a string: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – JLRishe May 28 '16 at 17:28
  • @JLRishe You're right. Guess it just feels odd coming from C# where an actual type would be returned. – G. Deward May 28 '16 at 17:29
  • 2
    Nothing here you couldn't have researched yourself easily – charlietfl May 28 '16 at 17:31

1 Answers1

2

== is a soft compare, but typeof always returns a string.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

Kittsil
  • 2,349
  • 13
  • 22