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.

Community
  • 1
  • 1
pimvdb
  • 151,816
  • 78
  • 307
  • 352

3 Answers3

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
Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
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.

eapen
  • 579
  • 6
  • 15
  • 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. – pimvdb Dec 27 '10 at 19:12
  • It doesn't seem right to me either, but I was testing in Firebug and it seemed to remove the operator. – eapen Dec 27 '10 at 19:17
  • You are right, it doesn't delete it. I will update my answer above with a possible new method. – eapen Dec 27 '10 at 19:19
-1

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

if (a['foo'])
    alert("a['foo'] does exist.");
EinLama
  • 2,376
  • 1
  • 14
  • 10
  • 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. – pimvdb Dec 27 '10 at 19:16
  • 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. – EinLama Dec 27 '10 at 19:20
  • 1
    This technique fails if the value of a.foo is falsy. – lawnsea Dec 27 '10 at 19:22
  • You are right, I didn't consider that. – EinLama Dec 27 '10 at 19:24