0

I know the best way to check if a variable is undefined is

if ( typeof( something ) == "undefined") 

What I don't understand is when is a variable undefined and when is an object undefined. For instance when I console.log() the a variable I get

Object {detailedView: undefined}

My question is why I am getting this and not a plain undefined.

3 Answers 3

2

a isn't undefined. It's defined. It's an object. That object just so happens to contain a property that is undefined, but the variable itself isn't undefined.

something isn't defined, so it's undefined.

Sign up to request clarification or add additional context in comments.

Comments

1

There are two things here: the "value" undefined, which is a value that a variable can point to when it has been declared but not assigned anything yet (i.e. var a;), or when it's been assigned something that doesn't actually have a value or exists, and there is the string "undefined", which is a string similar to "monkey" or "collywobble".

In your conditional, you're testing to see what the result of the typeof operator is, which is a string "object" or "function", or in this case "undefined". Those are just words:

if(typeof a == "undefined")

is the same as testing

if(a == undefined)

So, when you console.log the actual object, you'll see it has a value undefined, rather than being a string "undefined".

Comments

1

I believe you're asking about the difference between "undefined variables" (variables never declared) and "undefined values" (the value undefined inside a variable or property).

You define/declare a variable with the var keyword:

var myVariable;

If you just do that, the value of that variable is undefined:

console.log(myVariable); // undefined

If you don't declare a variable, you cannot use it:

console.log(myOtherVariable); // throws a ReferenceError

... except in typeof:

typeof myOtherVariable == "undefined"; // true

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.