How can I compare a non-existing JavaScript object to undefined without getting a Reference Error?

Fawkes5 picture Fawkes5 · Jul 8, 2012 · Viewed 14.5k times · Source

I want to boolean to come out of this expression

(task === undefined);

where task is arbitrary and doesn’t appear in the code at all.

However, when I run this in rhino, I get a reference Error. I WANT TRUE

Why don’t I get true?

I want to check if a particular variable has been defined. How do I do it then if this doesn't work?

Answer

Ned Batchelder picture Ned Batchelder · Jul 8, 2012

Use this:

(typeof task === "undefined")

When you use (task === undefined), Javascript needs to find the value of task to see if it is the same as undefined, but it can't look up the name because it doesn't exist, giving you the reference error. typeof is special in that it can safely return the type of a name that doesn't exist.