views:

3780

answers:

3

In PHP you can do if(isset($array['foo'])) { ... }. In Javascript you often use if(array.foo) { ... } to do the same, but this is not exactly the same statement. The condition will also evaluate to false if array.foo does exists but is null or false (and probably other values as well).

What is the perfect equivalent of PHP's isset in Javascript?

In a broader sense, a general, complete guide on Javascript's handling of variables that don't exist, variables without a value, etc. would be convenient.

+14  A: 

I generally use the typeof operator:

if (typeof obj.foo != 'undefined') {
  // ..
}

It will return "undefined" either if the property doesn't exist or it's value is undefined.

(See also: Difference between undefined and not being defined.)

There are other ways to figure out if a property exists on an object, like the hasOwnProperty method:

if (obj.hasOwnProperty('foo')) {
  //..
}

And the in operator:

if ('foo' in obj) {
  //..
}

The difference between the last two, is that the hasOwnProperty method, will check if the property exist physically on the object (the property is not inherited).

The in operator will check on all the properties reachable up in the prototype chain, e.g.:

var obj = { foo: 'bar'};

obj.hasOwnProperty('foo'); // true
obj.hasOwnProperty('toString'); // false
'toString' in obj; // true

As you can see, hasOwnProperty returns false and the in operator returns true when checking the toString method, this method is defined up in the prototype chain, because obj inherits form Object.prototype.

CMS
Why use `typeof` rather than `if( obj.foo !== undefined )` ?
Matt Ball
I personally don't use it too much because the `undefined` constant is not part of the ECMA Standard, however is not bad to use it and you will find it on *almost* all the implementations...
CMS
Ah. One day I will write a piece of truly cross-browser Javascript. Until then...
Matt Ball
Shouldn't that be `obj.hasOwnProperty('foo')`, not `obj.hasOwnProperty('bar')`?
donut
@donut: Yes thanks!, it was a typo!
CMS
Great answer CMS!
alcuadrado
@alcuadrado: Thank you! -- Saludos hasta Argentina!
CMS
A: 
if (!('foo' in obj)) {
  // not set.
}
KennyTM
A: 

Should work for ya:

//Function to test if variable is unset/null
function isset(me)
{
 if (me == null || me == '')
  return 0;
 else
  return 1;
}

It does assume that you have at least declared the variable like a good programmer before hand (null if nothing else).

Boondoklife
There are so many things wrong with this that it hurts.
Stefan Kendall