7

what is the best usage for the "typeof" JavaScript function?

if (typeof (myvar) == 'undefined') { 
//or
if (typeof (myvar) == undefined) { 
//or
if (typeof myvar == 'undefined') { 
//or
if (typeof myvar == undefined) { 

Thanks

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
Tech4Wilco
  • 6,740
  • 5
  • 46
  • 81
  • why are you doing this? you should just do `myvar === undefined`. – Daniel A. White Oct 07 '11 at 17:02
  • possible duplicate of [How can I determine if a JavaScript variable is defined in a page?](http://stackoverflow.com/questions/138669/how-can-i-determine-if-a-javascript-variable-is-defined-in-a-page) – Vivin Paliath Oct 07 '11 at 17:03
  • 2
    @DanielA.White If `myvar` hasn't been declared, your code would throw `ReferenceError`. – duri Oct 07 '11 at 17:03

2 Answers2

14

typeof is an operator, not a function, and returns a string; so do not use parentheses and do compare it to a string.

When you compare things, avoid type coercion unless you need it (i.e. use === not ==).

if (typeof myvar === 'undefined') { 
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

Use strict comparison (===), and quote "undefined":

if (typeof myvar === "undefined") {}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390