ExploreOurteamtrainingCourses (3)

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…

Explore JavaScript Courses

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

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:
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…

Explore JavaScript Courses

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):

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: http://codepen.io/anon/pen/EPeNmE?editors=0012

Kyle Pennell
Kyle Pennell is the editor of appendTo.com.