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

3
  • why are you doing this? you should just do myvar === undefined. Commented Oct 7, 2011 at 17:02
  • possible duplicate of How can I determine if a JavaScript variable is defined in a page? Commented Oct 7, 2011 at 17:03
  • 2
    @DanielA.White If myvar hasn't been declared, your code would throw ReferenceError. Commented Oct 7, 2011 at 17:03

2 Answers 2

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') { 
Sign up to request clarification or add additional context in comments.

Comments

4

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

if (typeof myvar === "undefined") {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.