How to Check if JavaScript Object Has Key

Table of Contents

In this post we will go over how to check if a JS object has a key.

3 Ways to Check if a JavaScript Object has a Key

  1. Use the “in” keyword
  2. Use the .hasOwnProperty(“keyName”) method
  3. Try to use the key

Quick Answer

Here is a code snippet you can use if you are just looking for a quick answer.

var keyExists = someObject.hasOwnProperty("keyName");

Towards the end we are also going to use the techniques from this guide to build a custom application.

How to Check if JavaScript Object has Key

There are various ways you can use JavaScript to check if a key exists in an object. These methods don’t all work the same way.

1. Check using the “in” keyword

 var hasKey = "apple" in fruitPrices;

The example above will store true in the variable valueForKey if the key “apple” exists in the object “fruitPrices”. The in keyword is one of the ways to check if an object has a key.

An important detail of the in keyword is that it will return true for inherited properties. So if you need to check if an object contains a property, including properties that it has inherited from its parents then this is what you should use.

2. Using .hasOwnProperty(nameOfKey) to check for key

Another way to check if a JS object has a key is to use the .hasOwnProperty(..) method.

var hasKey = someObject.hasOwnProperty("keyName");

This method will tell you if the property exists on the object itself, and will return false if the property is gained through inheritance.

An important detail here is that this does not check the prototype chain. This method will only tell you if this particular object has the property or not. That means if you don’t want to check if the parent has the key, then you should be using this method. This is the way that most people probably want to look for the key, as the in keyword can cause hard to find bugs if you don’t know about the inherited property detail.

3. Checking if key exists by using the the key

var valueForKey = fruitPrices["apple"] !== undefined;

You could check if you get a value back when using the key itself. If using this method though you should be aware that the value that is stored for the key could be the “value” of undefined, so this method does not work if it is a legal value.

You can use either of the three examples above depending on your need. Under each code snippet there are some important details regarding how they behave. You should read those to make sure you pick the method that behaves the way want it to. You should probably use either number #2 or #1, with .hasOwnProperty(..) being more likely.

Example project where we check if JS object has key

We will now go a little more in depth on the different ways to check for a key, before we can get to the examples we need to create the object that we will be using.

How to create the object

You are able to create objects that contains key value pairs in JavaScript. They function much like they do in other languages, you are able to look up a value if you provide the key. This is an excellent way of storing values that you want to look up quickly, as you can easily check if an object contains a key or a value using JavaScript.

First create the object that will store your values. We will be using an object where the keys are names of fruits, and the values are the prices of the fruits.

var fruitPrices = {
    apple : 2,
    banana : 1.55,
    orange : 1.35,
    avocado : 3
};

If you want to follow along you can copy and paste the code above into the console in your browser. If you then type in the name of the object you should see something like in the image below.

Image of the object and all the key value pairs inside it

Now that we have our object we want to check if the object has a value for a given key. You can do this using the following syntax.

Using the in Keyword to Check if Object Contains Key

var valueForKey = "apple" in fruitPrices;

The above code will store true in the variable valueForKey. You can also type “apple” in fruitPrices; into your console and you can see that it prints true. Make sure that you still have the fruitPrices object in your console too.

We can use this technique to create a function that takes in an obejct and the key we are looking for. The function will return true if the key exists, otherwise false.

function objectHasKey(key, object){
    return key in object;
}
console.log(objectHasKey("apple", fruitPrices)); // Prints true
console.log(objectHasKey("test", learnLanguage)); // Prints false

Checking if a key already exists can actually be quite useful sometimes.  Lets say you are looping over a list of words, and you want to count how many times each word appears. You could create an object where the key was the word and the value was the count. Each time you see a word you would check to see if it was in the object, if it is then you increment the value. If it is not already in the object then you add the new word and a count of 1 as a new key value pair.

Using .hasOwnProperty(key) to check if key exists

We can use the .hasOwnProperty(“key”) function to check if an object has a given property.

console.log(fruitPrices.hasOwnProperty("apple")); // prints true
console.log(fruitPrices.hasOwnProperty("strawberry")); // prints false

As with the previous example, we can use this technique to create a function we can use.

function objectHasKey2(key, object){
    return object.hasOwnProperty(key);
}

console.log(objectHasKey2("avocado", fruitPrices)); // Prints true
console.log(objectHasKey2("toast", fruitPrices)); // Prints false

What is special about this method is that it will only work if the object itself has the property, and it is not gained through inheritance. This might be useful for certain use cases.

Using the key itself to Check if the object contains the key

You can use the key itself to see if it exists on an object. If using this method you should be aware that in some cases, the value “undefined” might be valid case and this method would not work all the time then.

fruitPrices["apple"];

By passing the key “apple” to the object it will return the corresponding value which is 2.

Looking up the value in an object using the key

Here is a second example with just the code and a different object.

var learnLanguage = {
    javaScript : true,
    scala : false,
    cSharp : true,
    java : true
};

var javaScriptExists = "javaScript " in learnLanguage ;
console.log("Learn Javascript? " + learnLanguage["javascript"] ? "Yes" : "No" );

// Prints "Yes"

We can also turn this into a function.

function objectHasKey3(key, object){
    return object[key] !== undefined;
}

console.log(objectHasKey3("java", learnLanguage)); // Returns true
console.log(objectHasKey3("php", learnLanguage)); // Returns false

Because of the restrictions of both the .hasOwnProperty and using the key, I recommend you use the “in” keyword to check if an object has a key. You can use these other methods if your use case calls for their specific properties.

Building an Application where we have to check if the object has a given key

We are going to build a shopping list app. We will have input where you can add items to the list, and a search box for finding the amount we want to buy for the given key. The shopping list will be an object where the key is what we are going to buy, and the value will be the number of items we want.

You can find a working version of the app embedded at the bottom of this page.

1. Creating our HTML elements

Lets start by creating the HTML structure that our app needs.

Wee need the following elements

  1. Two input boxes and a button for adding elements to our shopping list
  2. An input box and a button for searching for our item
<div class="exampleContainer">
    <div class="userInputContainer section">
        <input id="itemName" placeholder="Item name" />
        <input id="itemAmount" placeholder="number of items" />
        <button class="exampleButton" id="addItem">Add Item</button>
    </div>

    <div class="searchContainer section">
        <input id="searchBox" placeholder="Search" />
        <button class="exampleButton" id="search">Search</button>
        <label id="searchResult"></label>
    </div>
</div>

2. Adding CSS

Now we are going to add some styling to make the application look a little better.

<style>
    .section{
        margin: 20px 0px;
    }

    .exampleContainer{
        padding: 10px;
        margin: 20px 0px;
        border: 1px dotted;
    }

    .exampleButton{
        background-color: #b36038 !important; //Needed because of the WP theme I am using
    }
  
</style>

3. Adding logic with JavaScript

Now we just need to add our logic using JS. We have to create a shopping list class as well. You could extend the functionality of this application by adding more features to the class. It could for example have a “display” function which could list all the items in an ordered list somewhere on the page.

class List{
    listItems;

    constructor(){
        this.listItems = {};
    }

    addItem(item, amount){
        if(item != "" && !isNaN(amount)){
            this.listItems[item] = amount;
        }
    }

    getAmount(item){
        var amount = 0;
        if(this.containsItem(item)){
            amount = this.listItems[item];
        }

        return amount;
    }

    containsItem(item){
        return item in this.listItems;
    }
}

var shoppingList = new List();

var addButton = document.getElementById("addItem");
var searchButton = document.getElementById("search");

addButton.addEventListener("click", function(){
    var name = getInput("itemName");
    var amount= getInput("itemAmount");
    shoppingList.addItem(name, amount);

    clearInput("itemName");
    clearInput("itemAmount");
});

searchButton.addEventListener("click", function(){
    var name = getInput("searchBox");
    var result = shoppingList.getAmount(name);
    document.getElementById("searchResult").innerHTML = "You want " + result + " of " + name;
});

function getInput(id){
    return document.getElementById(id).value;
}

function clearInput(id){
    document.getElementById(id).value = "";
}

Working Application

I have embedded the code above into the page below so that you can play around with it. Explore the code to see what limitations it might have, and as an exercise you could try to add a feature or two.

Related Guides