Till the date, there are 3 ways to check if an object has a property :
- Compare with
typeof
andundefined
. - Use
hasOwnProperty
method. - Use
in
keyword.
Comparison with typeof
Check if the type of a property is undefined, is one of the most common practices when developers check if an object has a property.
typeof
function returns a string with the name of the type of the variable as a first parameter (Boolean
, Object
, undefined
etc). Therefore, you'll need only to compare the value of the property that you want with "undefined"
.
var myObject = {
hello: "Hey"
};
if("undefined" === typeof(myObject["hello"])){
// The property DOESN'T exists
}else{
// The property exists
}
// Or ...
if(typeof(myObject.hello) === "undefined"){
// The property DOESN'T exists
}else{
// The property exists
}
// Or ...
if(typeof(myObject.hello) !== "undefined"){
// The property exists
}else{
// The property DOESN'T exists
}
Note: If the object has the property with value as undefined, typeof
is not recommendable. To prevent confusions, use hasOwnProperty instead if you use undefined instead of null in your objects.
hasOwnProperty
A Javascript object has normally the hasOwnProperty native method. The hasOwnProperty method returns a boolean indicating whether the object has the specified property as first parameter.
Unlike the in
operator, this method does not check down the object's prototype chain.
var myObject = {
hello: "This is my hello string"
};
if(myObject.hasOwnProperty("hello")){
// myObject has the hello property
}else{
// myObject doesn't has hello property
}
// False
var hasPropertyHello = myObject.hasOwnProperty("monkey");
// Use hasOwnProperty in arrays too using the index
["hello"].hasOwnProperty(0); // true
// But no the value
["hello"].hasOwnProperty("hello"); // false
in
The in operator returns true if the specified property is in the specified object. Note that you can use in
either in object and arrays.
var myObject = {
hello:"Hello message"
};
if("hello" in myObject){
// Hello property exists
}else{
// Hello property exists
}
// False
var isInObject = ("trello" in myObject);
// Use in in arrays too using the index
(0 in ["hello"]); // true
// But not the value
("hello" in ["hello"]); // false
Which method is faster
If we really want to know which is faster, you'll notice the difference only if you work with an extense loop and huge objects.
According to the tests, the comparison with typeof
seems to be pretty faster compared with hasOwnProperty
and in
.
The execution of the previous snippets 1000000 (1M) times, shows that the in
and hasOwnProperty
methods take approximately twice than the time required by the comparison with typeof
and undefined
.
Finally, what method should i use ?. The method doesn't matters unless you work with huge datasets. Have fun