Skip to content
Fix Code Error

JavaScript isset() equivalent

March 13, 2021 by Code Error
Posted By: Anonymous

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.

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.

Answered By: Anonymous

Related Articles

  • error LNK2005: ✘✘✘ already defined in…
  • Reference — What does this symbol mean in PHP?
  • What does this symbol mean in JavaScript?
  • Making Make Automatically Compile Objs from Headers into…
  • How do I include certain conditions in SQL Count
  • "Notice: Undefined variable", "Notice: Undefined index", and…
  • Form field border-radius is not working only on the last…
  • How do I keep only the first map and when the game is…
  • Convert JavaScript string in dot notation into an object…
  • Get the name of an object's type

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Get list of databases from SQL Server

Next Post:

if…else within JSP or JSTL

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error