javascript: best way of checking if object has a certain element or property?
Let's check the reliability of these ways of checking if object has a certain element or property:
This can fail if Boolean(person.age)
is false
if (person.age) { ... }
This can fail if person.age
is null
or undefined
if (person.age != undefined) { ... }
These can fail if person.age
is undefined
if (person.age !== undefined) { ... }
if (typeof(person.age) != 'undefined') { ... }
On the other hand, the hasOwnProperty() method returns a boolean
indicating whether the object has the specified property as own (not inherited) property. So It does not depend on the value of person.age
property. So it is the best way here
if (person.hasOwnProperty('age')) { ... }
If you want to go further and check if an object has a property on it that is iterable(all properties including own properties as well as the inherited ones) then using for..in
loop will give you the desired result.
RocketNuts
Updated on June 05, 2022Comments
-
RocketNuts almost 2 years
Suppose I have this:
var person = { "name": "John Doe", "email": "[email protected]" };
This object only has two elements called
name
andemail
. Some persons also have an elementage
, but this particular person doesn't. What's the best way to check this?if (person.age) { ... }
if (person.age != undefined) { ... }
if (person.age !== undefined) { ... }
if (typeof(person.age) != 'undefined') { ... }
if (person.hasOwnProperty('age')) { ... }
I know all these don't do the same, e.g.
if (person.age)
would also fail ifage
does exist but it'sfalse
ornull
or''
or0
. And I wonder if some aren't just flat out wrong.Note that
person
is known to be an existing object here, butperson.age
may or may not exist.-
Dhaval Marthak over 6 yearsto me
person.hasOwnProperty('age')
:) value of the property is a different thing! -
Bergi over 6 yearsSo what do you want to check for exactly? That the property exists? "has a certain value", as in your question title, would be completely different thing.
-
Bergi over 6 yearsI guess
if (typeof person.age == "number")
is what you'll be looking for. -
RocketNuts over 6 years@Bergi right, that was confusing, I changed 'value' to 'element' in the title. Yes I meant just to check if the property exists.
-
Bergi over 6 years@RocketNuts Then use
hasOwnProperty
orin
(depending on whether you care if it's an own property or not). If you also care about the type of the property, usetypeof
.
-
Bergi over 6 yearsThe OP knows that already, it's in his list of options. Why should he use
hasOwnProperty
? -
Bergi over 6 yearsThe OP knows that already, it's in his list of options. Why should he use
hasOwnProperty
? -
Bergi over 6 yearsI saw the edit, but am still missing the explanation.