Walker Farrow
Walker Farrow

Reputation: 3905

What is the difference between "defined" and defined in javascript?

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!

Upvotes: 2

Views: 79

Answers (2)

trex005
trex005

Reputation: 5115

"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.

Upvotes: 0

error
error

Reputation: 756

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).

Upvotes: 8

Related Questions