Consider that you have a student with her roll number, name, mark, and attendance as shown below in the code block. And you try to access the property marksPercentage
.
const studentMaya = {
rollNo: "1",
firstName: "Maya",
lastName: "Devi",
marksPercentage: "75%",
attendancePercentage: "90"
}
But if the property marksPercentage
doesn't exist there, you might get an error. That's why you need to check if a key exists in JavaScript.
In this article, You will learn different approaches to check if the key exists in javascript objects and arrays, including the in
operator, hasOwnProperty
method, Object.keys
method, typeof
operator, checking for undefined, and optional chaining.
Pre-requisites
Table of Contents
Checking If a Key Exists Using the in
Operator
- The
in
operator is one of the simplest and most commonly used methods to check if a key exists in a JavaScript object. Thein
operator returnstrue
if the specified property, also called key, exists in the object.
Syntax:
key in object
Example:
const car = { make: 'Toyota', model: 'Camry' };
console.log('make' in car); // true
console.log('year' in car); // false
- The
in
operator checks both the object properties and its inherited properties. For example:
const person = { name: 'John' };
console.log('toString' in person); // true
- In the above code block, The
toString
method exists in the prototype chain of theperson
object.
Note:
- Use the
in
operator when you need to check for keys that might be inherited from the prototype.- Avoid using it when you only want to check for properties directly on the object.
Checking If a Key Exists Using the hasOwnProperty
Method
- The
hasOwnProperty
method is another common way to check the existence of a key in an object. ThehasOwnProperty
method also checks whether the object has the specified property.
Syntax:
object.hasOwnProperty(key)
Example:
const car = { make: 'Toyota', model: 'Camry' };
console.log(car.hasOwnProperty('make')); // true
console.log(car.hasOwnProperty('year')); // false
- The
hasOwnProperty
method only checks the object's properties.
// define `car` object
const car = { make: 'Toyota' };
console.log(car.hasOwnProperty('make')); // true
console.log(car.hasOwnProperty('toString')); // false
- In the above code block, the
make
property is directly related to thecar
object. So thehasOwnProperty
method returnstrue
. - On the other hand
toString
method is inherited fromObject.prototype
. Hence, thehasOwnProperty
method returnsfalse
Note: Using
hasOwnProperty
is a better option when you are not considering checking the inherited properties of an object.
Using Object.keys
and includes
Methods to Check If a Key Exists
- The
Object.keys
method returns an array of a given object's properties. Just like you do using thefor
loop. TheObject.keys
method can also be used to check if a key exists with the help of theincludes
method.
Syntax:
Object.keys(object)
Example:
const car = { make: 'Toyota', model: 'Camry' };
const arrayOfCarProperty = Object.keys(car); // ['make', 'model']
console.log(arrayOfCarProperty.includes('make')); // true
- In the above code block, you use the
Object.keys
method to create an array of keys and assign it to the variablearrayOfCarProperty
. - Then, you use the
includes
method that returnstrue
because themake
property exists in thearrayOfCarProperty
array.
Checking If a Key Exists Using typeof
Operator
- The
typeof
operator also helps to check if a key exists by checking if its value isundefined
.
Syntax:
typeof object[key] !== 'undefined'
Example:
const car = { make: 'Toyota', model: 'Camry' };
console.log(typeof car.make === 'undefined'); // false
console.log(typeof car.year === 'undefined'); // true
- In the code block above, you are checking the value of the
make
property for thecar
object usingtypeof
, which returnsfalse
. This happens because the value of themake
property is notundefined
. - On the other hand, the value of the
year
property for thecar
object isundefined
or doesn't exist.
Note:
- Using
typeof
method, you can only checks forundefined
values, not if the property is truly present.- It can be misleading if the property's value is
undefined
as shown below:const car = { make: 'Toyota', year: undefined }; console.log(typeof car.make === 'undefined'); // false console.log(typeof car.year === 'undefined'); // true
- In the above code block, the
year
property exists incar
object, but the value of theyear
property is undefined. Hencetypeof
method returns true.- Therefore, it is not recmomended to use the
typeof
method to check if key exists untill not neccesary
Using Optional Chaining to Check If a Key Exists
Optional chaining (?.
) is a modern feature in JavaScript that allows safe access to nested properties. If any part of the chain is null
or undefined
, the expression short-circuits and returns undefined
.
Syntax:
object?.key
Example:
const car = { make: 'Toyota', details: { model: 'Corolla' } };
console.log(car.details?.model); // 'Corolla'
console.log(car.details?.year); // undefined
Conclusion
In conclusion, there are multiple methods to check if a key exists in JavaScript objects, each suited for different scenarios.
in
operator: Quick and easy, checks prototype chain.hasOwnProperty
method: Checks only own properties, safer in many contexts.Object.keys
method: Useful when working with key arrays, more performance-intensive.typeof
operator: Simple check forundefined
, but with some limitations.- Checking for
undefined
: Direct but doesn't distinguish between non-existent andundefined
values. - Optional chaining: Safe access to nested properties, prevents runtime errors.
Each method has its advantages and should be chosen based on the specific needs of your code. Understanding these methods will help you write more robust and error-free JavaScript.