How to Check if an Object has a Specific Property in JavaScript
There are several methods of checking whether the object has a property or not in JavaScript. Let’s quickly explore them and find the fastest one.
The typeof Function
Most of the developers use the typeof method to check if the type of the property is undefined or not. If the object has the property with the undefined value, typeof is not recommended.
The hasOwnProperty Method
Javascript object provides the hasOwnProperty native method. The method returns a boolean indicating if the object has the specified property as a first parameter.
The in Operator
The in operator returns true if it finds the specified property in the object.
To understand which method is faster, you should work with huge objects. Tests show that typeof is much faster compared to the hasOwnProperty and in methods.
The typeof Operator
The typeof operator helps to get the data type of its operand. The operand can be a literal or a data structure (an object, a function, or a variable). The typeof function returns a string with the name of the type of the variable as a first parameter (object, boolean, undefined, etc.).
hasOwnProperty vs in
The hasOwnProperty method returns a boolean, which shows whether the object contains the specified property or not.
This method determines whether the object has the specified property as a direct property of that object. Unlike the in operator, hasOwnProperty does not check for a property in the object's prototype chain. If an object is an Array, this method can check whether an index exists. If the specified property exists in the object or its prototype chain, the in operator returns true.