Method 1: Using the “in” Operator to Find the Existence of a Key
We can use the “in” operator to check for a particular key in an object, just like we can use it to find the existence of a particular character in a string. To demonstrate this, we are going to need an object there create an object with the following lines of code:
As you can see, this object is about a person and includes details like the first name, last name, age, and salary. Suppose that we want to check whether or not the key “age” is present in our personObject. In that case, search for age in personObject and set the return value in a new variable:
After that, we can simply print the value inside the existence variable on the terminal using the console log function like:
After that, simply execute the program and observe the following result on the terminal:
The true value in the terminal means that the key age does exist in the object personObject.
After that, we also want to check for a key that is not present in the personObject. For this, we are going to use the in operator to find the key “martialStatus” in the personObject like:
And then again, we can simply pass this existence variable to the console log function to print the result on the terminal like:
Execute the program and observe the following result from the terminal:
As you can see, the result was false meaning that there is no such key as martialStatus inside our personObject.
Method 2: Using the “hasOwnProperty()” Method With the Object
To demonstrate hasOwnProperty(), create an object using the following lines of code:
As you can already tell, the above lines are to create an object of a car. What we want to find is the presence of the key “make” in the object “car”. For this, apply the hasOwnProperty() method on the car object with the help of a dot operator and pass in the key “make” in its argument like:
After that, simply pass the existence variable in the console log function to display the result on the terminal like:
Execute the program for the following outcome:
The output on the terminal is true, which means the car object contains the key make. After that, let’s check for the existence of the key “mileage” in our car object. For this, simply pass the key as mileage in the hasOwnProperty() method’s argument:
To show the result on the terminal, simply pass the variable “existence” in the console log function:
Execute the program and observe the following output:
The output shows that there is no such key as mileage in the object car.