-1

Perhaps a somewhat theoretical question, but to check if a variable exists or not, this is most commonly advised:

typeof(var)==='undefined' or typeof(var)!=='undefined'

How does this differ from typeof(var)=='undefined' (or typeof(var)!='undefined') ?

I mean === vs ==. Or !== vs !=. I know this normally means comparison of type as well as value, but in this case, typeof(something) always evaluates to a string, right?

Is there any scenario possible where typeof(var)==='undefined' and typeof(var)=='undefined' are not the same?

RocketNuts
  • 9,958
  • 11
  • 47
  • 88
  • 1
    The answer on this thread should help to clarify... http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons – Charlie74 Sep 14 '15 at 18:51
  • 1
    You're right. Some people like to always use `===` to be consistent (or they have read somewhere that `==` is pure evil and should be avoided at all cost). – pawel Sep 14 '15 at 18:54
  • Quick note: `typeof` is an operator, not a function. You can omit those parenthesis. – Oka Sep 14 '15 at 18:57
  • Yes, the typeof operator always returns a String as mentioned here: http://www.w3schools.com/js/js_type_conversion.asp. I can't think on a scenario where does two scenarios are not the same only because typeof returns string – Erick Sep 14 '15 at 18:58

3 Answers3

0

There is really no difference thus typeof returns a string.

Use === and !== when you want to avoid automatic conversions.

Examples:

alert(1!='1')//false
alert(1!=='1')//true
alert('1'!='1')//false
alert('1'!=='1')//false
alert(true==1)//true
alert(true===1)//false
Pavel Gatnar
  • 3,987
  • 2
  • 19
  • 29
0

The '===' and '!==' operators are a bit faster, so in most cases, these should be used instead of '==' or '!='.

BoltKey
  • 1,994
  • 1
  • 14
  • 26
-1

As for the != part, the ! is to be taken as a NOT. typeof var !=='undefined' => if typeof var is not undefined

Makerimages
  • 384
  • 6
  • 27
  • Thanks, yes I knew, I just wondered about the difference between `typeof var !== 'undefined'` and `typeof var != 'undefined'`, but apparently there is none. – RocketNuts Sep 14 '15 at 19:02
  • A matter of preference, here merely. BUT in some languages, it's proper to use `==` in an if statement, as that checks, while just a single `=` sets (always return strue in the if). Good to tell them apart. – Makerimages Sep 14 '15 at 19:04