JavaScript objects are popular data structures used widely by web developers these days. They allow you to store diverse data types in a compact manner as key-value pairs. They allow you to easily access data using keys. However, if you try to access a key that does not exist then web browser may return undefined or throw an error and may even stop code execution. So it is always recommended to check if key exists in JavaScript object before you try to access it. There are several ways to solve this problem using JavaScript alone. In this article, we will learn different ways to check if a key exists in JavaScript object.
The Problem
Let us say you have the following JavaScript object.
var data = {'a':1,'b':2};
The above JS object contains two keys a and b. Let us say you try to access the value of key c which is not present in the above object.
console.log(data['c']); // prints undefined
In most modern web browsers like Chrome, the above code will return undefined value.
If you use the object notation, it may even give error.
console.log(data.3); // gives error
Absent Key vs Undefined Value
Before we proceed, it is important to understand the difference between the absence of a key in a JS object and the key having undefined value assigned to it. When you try to access a key that doesn’t exist, web browser will return undefined value. If the key is present but assigned undefined value, when you try to assign such a key, even that will return undefined. So you cannot rely on value being undefined to determine whether the key exists or not.
How to Check if Key Exists in JavaScript Object
Now let us look at different ways to check if key exists in JavaScript object. Let us say you have the following object.
var data = {'a':1,'b':2, 3:3, 4: undefined};
1. Using In Operator
The IN operator checks whether a key is present in a JS object. It returns true if the key is present, else it returns false. It is a very easy way to check if a key exists or not. Here is its syntax.
'key' in object
Here is the code to check if key c is present in data or not.
console.log('c' in data); // returns false
Please note, while using IN operator, if your keys are strings, then you need to mention the key within quotes. Otherwise, you will get an error. But if you have numeric key, then you will get the same result, with or without quotes.
console.log(3 in data); // returns true
console.log('3' in data); // returns true
2. Using hasOwnProperty()
Every JS object supports a built-in method hasOwnProperty() that accepts the key as an input argument and returns a Boolean value. It returns true if the key is present, else it returns false. Here is its syntax.
Object.hasOwnProperty(key);
Like in the case of IN operator, if you are looking for a string key, it needs to be within quotes. If you are looking for a numerical key, then you may or may not use quotes.
console.log(data.hasOwnProperty('c')); // returns false
console.log(data.hasOwnProperty('3')); // returns true
console.log(data.hasOwnProperty(3)); // returns true
3. Using hasOwn()
There is another method hasOwn() that is available for Object prototype. It checks an object for a key and returns Boolean value. It returns true if the key exists and false if the key does not exist. Here is its syntax.
Object.hasOwn(object, key);
Here are a few examples to check if key c and 3 are present in the data object or not.
console.log(Object.hasOwn(data,'c')); // returns false
console.log(Object.hasOwn(data,'3')); // returns true
console.log(Object.hasOwn(data,3)); // returns true
In this case also, strings and alphanumeric keys need to be within quotes whereas numeric keys may or may not be within quotes.
4. Using Keys()
The Object prototype supports keys() function that accepts an object as input and returns an array of all keys present in the object. You can use it along with includes() function to check if a specific key is present or not in it.
Object.keys(object_name).includes(key);
In the above code, Object.keys() returns an array of keys. Since every JS array supports includes() function, we can call it directly on the result of Object.keys(). Here are some examples to check if key exists in JS object using this method.
console.log(Object.keys(data).includes('c')); // prints false
console.log(Object.keys(data).includes('3')); // prints true
console.log(Object.keys(data).includes(3)); // prints false
In the above code, you will see that when we check if key=3 is present, it returns false, even though it is clearly present in the object. This is because Object.keys() returns an array of keys, where each key is present as a string, within quotes. So when we call includes() function on this array, you need to mention the key within quotes.
In other words, when you use this method, always specify the key to be searched, within quotes.
5. Using Double Bang Operator
You can also use double bang operator to check if the key exists or not. It returns true if the key exists, else it returns false. It also returns false, if the key exists but its value is undefined.
var data = {'a':1,'b':2,3:3,4:undefined};
console.log(!!data['c']); // prints false
console.log(!!data[3]); // prints true
console.log(!!data[4]); // prints false
In the above code, when we look for key c it returns false since the key is not present. When we look for key 3, it returns true since it is present. Lastly, when we look for key 4, it still returns false, since its value is set to undefined.
6. By accessing elements via Brackets
Another way to directly check if a key is present or not is to check if its value is undefined. In this case, we directly access the element with desired key, using brackets. Here is the syntax for it.
object[key]==undefined
Here is an example to illustrate its use.
console.log(data['c']==undefined); // prints true
For numeric keys, you may or may not use quotes.
console.log(data['3']==undefined); // prints false
console.log(data[3]==undefined); // prints false
As mentioned earlier, if any of the key has undefined value, then this method will return true.
var data = {'a':1,'b':2, 3:3, 4: undefined};
console.log(data[4] == undefined); // prints true
Please note, this solution will not work if the key is present but its value is set to undefined. In all other cases, it works much faster than above mentioned solutions.
7. By accessing elements via Objects
Similarly, you may also access keys using object notation and check if its value is undefined or not. This method works only if the key you are looking for starts with a character. Here is its syntax.
object.key == undefined
Here is an example to check if keys c and 3 exist in data object.
var data = {'a':1,'b':2, 3:3, 4: undefined};
console.log(data.c==undefined); // prints true
console.log(data.'3'==undefined); // gives error
console.log(data.3==undefined); // gives error
console.log(data.4==undefined); // gives error
console.log(data.c4==undefined); // prints true
Let us look at the above code in detail. The first equation prints true because key c is not present in the object. The second equation gives error because the object contains number 3 as key but we are looking for 3 within quotes. The third equation gives error even though 3 is one of the keys present in the object, because object notation supports only string keys. Fourth equation also gives error because 4 is not present as one of the keys. But the last equation prints true because the key you are looking for begins with a character.
This method also is much faster than most of the above methods. It works for all cases except when the key actually has undefined value, or if the key starts with a number.
8. Check Multiple Keys
If you want to check for the presence or absence or multiple keys, you can store them in an array, loop through the array, and in each iteration, use any of the above methods to individually check if the key is present in the object or not. Here is an example to check if keys 3 and 4 are present in the data object.
keys=[3, 4];
for(i in keys){
console.log(keys[i] in data);
}
Here is the output.
true // for 3
true // for 4
Conclusion
In this article, we have learnt several simple ways to easily check if a key exists or not in a JS object. You can use any of these methods but it is important to remember that in most cases, string or alphanumeric keys need to be mentioned within quotes whereas numeric keys may or may not be mentioned within quotes. Also, among them, accessing JS object as map or object (solutions #6 and #7), is the fastest way to check whether key exists or not. You can use any of these solutions as per your requirement.
Also read:
How to Insert Item In JS Array At Specific Index
What Does Strict Do in JavaScript
How to Check If Array Includes Value in JavaScript
Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.