2

When writing this in javascript, I have seen it written in two different ways:

if (typeof x === "undefined") {
// execute code here
}
if (typeof x === undefined) {
// execute code here
}

my question here is:

what is the difference between "undefined" and undefined. One is enclosed in quotes and the other is not.

Can anybody clarify this for me?

Thanks!

asked Jan 29, 2015 at 22:08
2
  • "undefined" is a string containing the letters u, n, d, etc... undefined (no quotes) is a javascript variable. Commented Jan 29, 2015 at 22:11
  • The first is a string, the second is a primitive value of undefined type Commented Jan 29, 2015 at 22:12

2 Answers 2

8

undefined is a value, 'undefined' is a string literal. The typeof operator returns a string that gives you the type. So typeof x returns the string name of the type of x.

Use if( x === undefined ) or if( typeof x === 'undefined' ) but never if( typeof x === undefined ) because typeof x will always return a string (which will never equal undefined).

answered Jan 29, 2015 at 22:11
Sign up to request clarification or add additional context in comments.

2 Comments

actually, undefined could be defined as "undefined" in which case if(typeof x === undefined) would evaluate identically to if(typeof x === "undefined")
If you do this, I will find you.
0

"undefined" is a string, and undefined is a variable containing the primitive value undefined (Thank you elclanrs).

if(typeof x === undefined) should only ever be able to return true if undefined is reassigned to a string matching the type of x.

Ionuț G. Stan
179k19 gold badges196 silver badges206 bronze badges
answered Jan 29, 2015 at 22:11

30 Comments

"is a variable, which is probably undefined" --- that's not correct
You can't set a variable with name undefined, it's a reserved global that represents undefinedness...
undefined is indeed a variable, that you can give any value you want, unless you use strict
@elclanrs "is indeed a varaible" --- as per specification or implementation?
@zerkms, actually, seems to be defined in the spec. ecma-international.org/ecma-262/5.1/#sec-15.1.1. I think we are talking about different things. undefined is a variable with value undefined which is of type Undefined
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.