JavaScript isset() equivalent

isset, javascript

Solution

I generally use the `typeof` operator:

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

It will return `"undefined"` either if the property doesn't exist or its 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')) {
  // your code here
}

And the `in` operator:

if ('foo' in obj) {
  // your code here
}

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`.

Problem

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 `false` or `0` (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. Update: 11 years and 11 months ago I posted this question, and wow, it still gets a lot of activity. Now, I'm pretty sure that when I wrote this, I only wanted to know how to check for the presence of a property in an associative array (a.k.a. dictionary), and as such the correct (for me) answers involve `hasOwnProperty` or the `in` operator. I wasn't interested in checking local or global variables. But while I remember that well, that intent is not quite clear in the question as written, or even directly contradicted by it! I never mentioned the associative array, and PHP's `isset` does also do those other things. Let this be a lesson to all of us about how important it is to properly state your requirements in a question, and also how global variables, local variables, object properties, dictionary keys and what-have-you aren't Huey, Dewey, and Louie. In the meantime (heh), many many people have provided answers to that effect as well, so for those of you who found this question through Google, well, I'm glad my vagueness helped in a way I guess. Anyway, just wanted to clarify that.

Original source

Related problems