0

Possible Duplicate:
How can I check whether a variable is defined in JavaScript?

Say we have a piece of code like this. How would one be able to check whether the variable does exist or not in the case its value might be undefined?

var a = { foo: 'bar' }
a['foo'] = undefined;
// now a['foo'] returns undefined, as it does exist and contains undefined as its value
delete a['foo']
// now a['foo'] still returns undefined, but it doesn't exist

Thanks.

0

3 Answers 3

4

For this you use the in operator.

var a = {'foo': undefined};
'foo' in a // returns true

delete a.foo;
'foo' in a // returns false

alternatively you can use Object.prototype.hasOwnProperty

var a = {'foo': undefined};
a.hasOwnProperty('foo') // returns true

delete a.foo;
a.hasOwnProperty('foo') // returns false
Sign up to request clarification or add additional context in comments.

Comments

1

Setting a['foo'] = undefined is equivalent to delete a['foo']

If you print the value of a['foo'] after setting it to undefined, you will see that it returns and empty variable/struct.

If you were trying to set a['foo'] to a string with "undefined", you could have used the "typeof" function to check if it is indeed undefined or if it is a string.

EDIT:

You can check if it exists or not using 'foo' in a

i.e.

'foo' in a // returns true after setting it to undefined 'foo' in a //returns false after deleting it.

3 Comments

I must say I do not fully agree with you. When setting it to undefined it stays in the object, but when deleting it is completely removed from the object.
It doesn't seem right to me either, but I was testing in Firebug and it seemed to remove the operator.
You are right, it doesn't delete it. I will update my answer above with a possible new method.
-1

You can check if the variable exists by passing it to an if-statement:

if (a['foo'])
    alert("a['foo'] does exist.");

4 Comments

I'm afraid this is not run even when I explicity set it to undefined. So this is no way to determine whether it is set to undefined or removed.
Why would you want to set it to undefined? Is there a special use case for this? You can delete the value or set it to null if you don't need it. By doing that, the above code works as expected. The use of ´undefined´ might lead to a poor API, unless alternatives are worse.
This technique fails if the value of a.foo is falsy.
You are right, I didn't consider that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.