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!
2 Answers 2
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).
"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.
30 Comments
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 strictundefined is a variable with value undefined which is of type Undefined
"undefined"is a string containing the lettersu,n,d, etc...undefined(no quotes) is a javascript variable.undefinedtype