In JavaScript, checking for the existence of a property within an object is a common task. Two methods that are frequently used for this purpose are hasOwnProperty() and the in operator. While both serve the purpose of determining whether a property exists in an object, they have distinct characteristics and use cases. This article explores the differences between hasOwnProperty() and the in operator.
What is hasOwnProperty()?
The hasOwnProperty() is a method that can be called on the any object to check if a specific property exists on that object itself rather than on its prototype chain.
Purpose: To determine if an object has the specific property as its own.
Returns: A boolean value.
Syntax
object.hasOwnProperty(property)
object: The object to check for the property.
property: The name of the property as a string.
Example
const obj = {
name: "kumar",
age: 30
};
console.log(obj.hasOwnProperty("name"));
console.log(obj.hasOwnProperty("toString"));
output :
true
falseCharacteristics
Checks only for the properties that belong directly to the object.
Ignores properties inherited from the prototype chain.
Applications
Useful when we need to the ensure a property is not inherited from the prototype.
Commonly used in the conjunction with the loops to the filter out inherited properties.
What is in?
The in operator checks whether a specified the property exists in an object either as a direct property or an inherited one.
Purpose: To determine if an object has a specific property whether directly or through its prototype chain.
Returns: A boolean value.
Syntax
property in object
property: The name of the property as the string.
object: The object to check for the property.
Example
const obj = {
name: "kumar",
age: 30
};
console.log("name" in obj);
console.log("toString" in obj);output :
true
trueCharacteristics
Checks for the properties both directly on the object and on its prototype chain.
Can detect inherited properties.
Applications
Join the conversation! Your thoughts help the community grow.