Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu March 14, 2023 › #Javascript #object

Checking if a key exists in a JavaScript object?

In this article, you will learn how to check if a key exists in a JavaScript object. Fortunately, there are several ways to check if a key exists in an object.

Check if key exists in object using in operator. #

The simplest way is to use the "in" operator which returns true or false depending on whether or not the specified property exists within an object.

<script>
 let myObj = {name : 'Apu', age : 20};
 console.log('name' in myObj); 
 console.log('country' in myObj);
</script>
  1. Output: "true" as name does exist inside of our example object (myObj).
  2. Output: "false" as country does not exist inside of our example object (myObj).

Check if key exists in object using hasOwnProperty() method. #

You can also use the hasOwnProperty() method. The hasOwnProperty() method in JavaScript can be used to check if a key exists in an object. It returns a boolean value which is true if the object has the specified property as its own property.

Here's an example of how to use hasOwnProperty() to check if a key exists in a JavaScript object.

<script>
 let myObj = {name : 'Apu', age : 20};
 if (myObj.hasOwnProperty('name')) {
   console.log('Name exists in myObj');
 } else{
   console.log('Name does not exist in myObj');
 }
</script>
Output : "Name exists in myObj" as name does exist inside of our example myObj.
save
listen
AI Answer
Write Your Answer
loading
back
View All