How to Check If a Key Exists in a JavaScript Object?

Follow us on LinkedIn for our latest data and tips!

JavaScript objects are comprised of properties. Properties in JavaScript are defined as pairs of keys and values. Keys can be generally thought of as the names of the values stored within JavaScript objects. There are a few different ways in which to check if a specific key exists within a certain object. And depending on how you want the information to be displayed, certain techniques are more advisable for returning results than others. Let’s unlock this a bit…

If you want to see all the enumerable keys contained within a JavaScript object, then you can use JavaScript’s Object.keys() method. The method looks and works like this:

Assume we have the object:

var obj = {
 name: "myObj",
 "data type": typeof this,
 logName: function() {
 logDataType: function() {
   console.log(this["data type"]);
obj.logName(); //myObj
obj.logDataType(); //object

To get all the enumerable keys contained within obj, simply pass obj to JavaScript’s Object.keys() method. The result of doing so will be this:

var x = Object.keys(obj);
console.log(x); //["name", "data type", "logName", "logDataType"]

What’s being stored in x, and subsequently logged to the console, is an array of all the enumerable keys contained within the obj object. After logging to the console, or otherwise displaying the results of Object.keys(), you can use any of JavaScript’s various array methods to access and manipulate the array of keys. Great!

Now… What if you’re interested in checking to see if a specific key exists within o newly created array of obj’s keys? You could go about doing so by using JavaScript’s Array.prototype.indexOf() method. That method would return the numerical index of a specified value (an object key, in our case) if that value is indeed present in the array upon which indexOf() is called (or it will return -1 if the specified value/key does not exist within the array). BUT there’s an even easier and more direct way to go about it…

In order to check if a specific key exists within a JavaScript object, you can use the Object.prototype.hasOwnProperty() method. This method is a property of all JavaScript objects; and to use it, you simply pass in a string with the name of the key for which you are checking. It looks like this (assume we’re still using our obj object):

var y = obj.hasOwnProperty("name");
console.log(y) //true
var z = obj.hasOwnProperty("color");
console.log(z); //false

Notice that this method returns the boolean true if there’s a match, and the boolean false if there is not.

So there you have it. Two ways to check if a key exists within a JavaScript object!

Code Examples: