In this guide, we will explore the limitations and functionalities associated with the hasOwnProperty method in JavaScript. Additionally, we will examine its practical applications and usage throughout the various sections.
Introduction
In JavaScript, the hasOwnProperty function is established as a property to verify if a specific object belongs to the designated project. When it is determined that the property is part of a valid object, it will return a Boolean value indicating the result, specifically either true or false.
Syntax
object.hasOwnProperty(propname)
Argument
Propname:
In this context, it is necessary to provide either the symbol or the name of the string, as this is the property location where it is verified whether the symbol or string is associated with the object. The verification is accomplished through the method outlined below.
var movie = {
name: 'iron man',
genre: 'super hit',
}
var song = {
name: 'cardigan',
}
movie.hasOwnProperty('name');
// returns true
movie.hasOwnProperty('type');
// returns false
song.hasOwnProperty('name');
// returns true
song.hasOwnProperty('status');
// returns false
A significant point to highlight is that the method hasOwnProperty typically disregards properties that are inherited. This implies that the method will yield true if the object possesses a property that is not inherited, and the property name is indicated by propname. Conversely, if it returns false, it indicates that the object either lacks a property with the given name or has inherited the property from its prototype object.
// Create an object
var o = new Object();
// Define a noninherited local property
o.x = 3.14;
o.hasOwnProperty("x");
// Returns true: x is a local property of o
o.hasOwnProperty("y");
// Returns false: o doesn't have a property y
o.hasOwnProperty("toString");
// Returns false: toString property is inherited
hasOwnProperty() will return true even if you define the undefined or null value.
let a = new Object();
a.propertyOne = null;
a.hasOwnProperty('propertyOne')
// output: true
a.propertyTwo = undefined;
a.hasOwnProperty('propertyTwo')
//Output: true
An additional benefit of utilizing the hasOwnProperty method is its capability to set up an object by subsequently implementing the idea of providing a string as the default parameter. It will promptly return true if the specified value exists within the object. Conversely, if the value is not present, it will yield false. This behavior can be illustrated with the code example provided below.
function Car(name) {
this.name = name;
}
Car.prototype.color = 'red';
const bmw = new Car('x1');
console.log(bmw.name);
// property found on object
console.log(bmw.color);
// color property found on prototype
console.log(bmw.hasOwnProperty('name'));
// name is found on the object itself
console.log(bmw.hasOwnProperty('color'));
// color property is not found on the object itself
In the code example provided earlier, the variable instantiates a new object of type Car. It can be concluded that the Car object is created with its properties and the name established through the constructor. While the color may not be explicitly defined within the object at the time of creation, it will consistently be accessible through the prototype chain. Consequently, the hasOwnProperty method will invariably yield true for the name property, but it will return false for the color property.
In terms of efficiency, the hasOwnProperty method operates seamlessly as it navigates through an object during iterations. At this point, we can conclude that the properties in question are exclusively associated with the object itself and do not relate to its prototype. This concept can be illustrated with the following code example.
// declaring a Car function
function Car(name) {
this.name = name;
}
// setting up new prop with prototype
Car.prototype.color = 'red';
// creating a new Car object
const BMW = new Car('x1');
// looping through every car prop including prototype as well
for (let car in BMW) {
car + ':', BMW[car];
}
/*
output: name: x1
output: color: red
*/
/**************************************/
/*will loop through only self properties of the object,
excludes property generated through prototype method */
for (let car in BMW) {
if (BMW.hasOwnProperty(car)) {
console.log(car + ':', BMW[car]);
}
}
// output: name:
When utilizing the hasOwnProperty method, it can become ineffective if an object defines a property with the same name, hasOwnProperty. To illustrate this point, consider the code example provided below.
var harrypotter = {
hasOwnProperty: function() {
return true;
}
};
// Outputs: true
console.log(harrypotter.hasOwnProperty("ridikulus"));
In the code example provided, it is clear that the harrypotter object already possesses the hasOwnProperty method. Consequently, it will not invoke object.prototype.hasOwnProperty. While one might think there could be situations where such an invocation could occur, it is likely to result in failure. Therefore, it is advisable to remain conscious of the potential for such calls. The following code snippet illustrates a solution to this issue.
// Returns false
Object.prototype.hasOwnProperty.call(harrypotter, "ridikulus");
In the preceding code example, it is evident that harrypotter implements its own version of hasOwnProperty. It deliberately avoids invoking Object.prototype.hasOwnProperty, as doing so could yield a false result in certain scenarios where the value is explicitly false, complicating the functionality. To illustrate this point, refer to the code snippet provided below.
// Returns false
Obje ct.prototype.hasOwnProperty.call(harrypotter, "ridikulus");
In addition to hasOwnProperty, there exists another method referred to as the "in" operator. This operator is utilized to determine whether a specific key exists within an object. However, it is crucial to recognize that the primary distinction between hasOwnProperty and the in operator is that the in operator does not differentiate between inherited properties and those that are directly associated with the object itself. This difference can be illustrated through the code example provided below.
var fantasyLit = {
tolkien: "The Lord of the Rings",
lewis: "The Chronicles of Narnia"
};
// Outputs: true
console.log("tolkien" in fantasyLit);
// Outputs: false
console.log("asimov" in fantasyLit);
// Outputs: true
console.log("constructor" in fantasyLit);
In the code segment presented above, it is clear that the 'in' operator adheres to the constructor property of Object.prototype, which serves as the inheritance source for all objects.
In addition to what has been stated, it is important to note that both approaches have their drawbacks. While both methods can efficiently provide details regarding a property that has already been defined, they fall short when it comes to indicating whether the property holds a genuine value.
Examine the subsequent code example which demonstrates how both approaches implement this workaround.
// Puts a "declared" property on the global object
// (window in browsers)
var declared;
// Outputs: true
console.log("declared" in window);
// Outputs: true
console.log(window.hasOwnProperty("declared"));
// Outputs: undefined
console.log(declared);
var obj = {
myUndefined: undefined
};
// Outputs: true
console.log("myUndefined" in obj);
// Outputs: true
console.log(obj.hasOwnProperty("myUndefined"));
// Outputs: undefined
console.log(obj.myUndefined);
Conclusion
In this tutorial, we explored the hasOwnProperty method in JavaScript. Generally speaking, this method serves as an excellent option for many developers to inquire about properties and to prevent complications associated with certain special keys, such as the constructor. It is advisable that when encountering an object with any property, the hasOwnProperty method should be utilized by default. If there exists a function designed to invoke a check on the object for the toString method, then the 'in' operator must be employed.