Checking in JavaScript if a key exists in an object is essential to ensure that the code runs smoothly without throwing errors. Objects are one of the 8 data types in JavaScript, and they are characterized by key-value pairs. In this guide you will learn all the methods how to perform a JavaScript check if key exists in a given object.
What are JS object keys?
In JavaScript objects, a key is a unique identifier used to access a specific value within that given object. As mentioned before, objects are collections of key-value pairs, where the key is a string (or symbol) that maps to a corresponding value. Thanks to keys, developers can easily store, access and manipulate object data.
The in operator method
The in operator method is a quick and easy way to check if a key exists in JavaScript objects. Besides checking for existence within an object, the in operator also allows you to access its prototype.
To check if a key exists in an object, write or console.log ´key´ in object. The code will return true if the key was found or false if it wasn’t found.
const student = {
name: "Mark Brown",
age: 23,
subject: "Mathematics",
grade: "A"
};
console.log(´subject´ in student); // true
console.log(´class´ in student); // false
JavaScriptAdvantages
- It is straightforward and easy to understand.
- It checks for inherited properties.
Disadvantages
- It may lead to confusion, returning true for keys inherited from the prototype chain.
The hasOwnProperty( ) method
The hasOwnProperty() method allows programmers to make a quick JavaScript check if key exists in a given object. Differently from the in operator, the hasOwnProperty() method will only check the object’s own properties, excluding any key inherited through its prototype chain.
const student = {
name: "Mark Brown",
age: 23,
subject: "Mathematics",
grade: "A"
};
console.log(student.hasOwnProperty('subject'); // true
console.log(student.hasOwnProperty('class'); // false
JavaScriptAdvantages
- It is relatively easy to understand.
- It allows for greater precision, considering the object’s own properties only.
- It can be more reliable when only the specific object should be considered.
Disadvantages
- It is less straightforward than the in operator.
- It may not be ideal, when the object prototype chain should be considered.
The Object.keys( ) method
Another way to check if a key exists in a JS object is using the Object.keys() method. Through calling Object.keys(), we get an array of all object’s property names. It is then possible to determine if a specific key is found amongst the items in the arrays using the array.includes() method. Here is an example.
const student = {
name: "Mark Brown",
age: 23,
subject: "Mathematics",
grade: "A"
};
console.log(Object.keys(student).includes('subject'); // true
console.log(Object.keys(student).includes('class'); // false
JavaScriptAdvantages
- It only considers the object’s own keys.
- It allows the use of other array methods.
Disadvantages
- It is less straightforward than the in operator or the hasOwnProperty() method.
- It is less efficient and more resource consuming due to the creation of a new array.
The undefined check
We can also see if a key exists in JS objects by checking if undefined is returned when attempting to access it. In JavaScript objects, accessing a key that does not exist returns undefined. In array instead, this throws an error.
const student = {
name: "Mark Brown",
age: 23,
subject: "Mathematics",
grade: "A"
};
console.log(student.subject !== undefined); // true
console.log(student.class !== undefined); // false
JavaScriptAdvantages
- It is easy to understand and relatively quick to perform.
Disadvantages
- It is not precise and may lead to errors, when an object contains a key that is explicitly undefined.
Optional chaining
In modern environments that support the latest ES2020 feature of optional chaining(‘?.’), you can check if key exists in object and if it has value. This method allows programmers to safely access nested keys without throwing unexpected errors if a key is not found. The optional chaining method returns the value for the given property only if this exists, otherwise it returns undefined.
const student = {
name: "Mark Brown",
age: 23,
subject: "Mathematics",
grade: "A"
};
console.log(student?.subject); // 'Mark Brown'
console.log(student?.class !== undefined); // undefined
JavaScriptAdvantages
- It is simple and coincise.
- It allows programs to access nested object keys without raising errors.
Disadvantages
- It requires ES2020 or later development environments.
Comparing performances
In this guide you have learnt that there are several ways to perform a JS check if key exists in an object. Each method has its own pros, cons, and impact on performance. While these differences are nearly negligible in small sized objects, performance implications become more noticeable when working with large dataset.
- hasOwnProperty() is more efficient because it only considers the given object, without attempting to access its prototype chain.
- in operator tends to consume more resources because it also considers all inherited keys of an object.
- Object.keys() is the least efficient method because it implies the creation of a new array.
Why should you check if a key exists?
When working with objects, checking that a key exists is essential for many reasons. First, it ensures that the required data is available before performing operations. This may prevent fatal errors from arising further down the code, and if unexpected problems do arise, it makes it easier to handle errors. Second, it allows for conditional execution of code based on the existence of specific key-value pairs. All things considered, performing a JavaScript check if key exists is a great practice in web development for debugging the code.
What is the best way to check if a keys exists in JavaScript objects?
There is no universal best method that to determine the existence of JS keys in objects. The choice depends on the specific use case and context of the application.
For most situations where you need to ensure that the key is an own property (not inherited), hasOwnProperty() is reliable, straightforward and highly efficient. If you want to check both own and inherited properties, the in operator is concise and still relatively effective. For modern JavaScript environments (ES2020+), optional chaining provides a concise and safe way to check if a key exists and access its value without raising errors.