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
inoperator is one of the simplest and most commonly used methods to check if a key exists in a JavaScript object. Theinoperator returnstrueif the specified property, also called key, exists in the object.
Syntax:
key in objectExample:
const car = { make: 'Toyota', model: 'Camry' };
console.log('make' in car); // true
console.log('year' in car); // false- The
inoperator 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
toStringmethod exists in the prototype chain of thepersonobject.
Note:
- Use the
inoperator 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
hasOwnPropertymethod is another common way to check the existence of a key in an object. ThehasOwnPropertymethod 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
hasOwnPropertymethod 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
makeproperty is directly related to thecarobject. So thehasOwnPropertymethod returnstrue. - On the other hand
toStringmethod is inherited fromObject.prototype. Hence, thehasOwnPropertymethod returnsfalse
Note: Using
hasOwnPropertyis 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.keysmethod returns an array of a given object's properties. Just like you do using theforloop. TheObject.keysmethod can also be used to check if a key exists with the help of theincludesmethod.
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.keysmethod to create an array of keys and assign it to the variablearrayOfCarProperty. - Then, you use the
includesmethod that returnstruebecause themakeproperty exists in thearrayOfCarPropertyarray.
Checking If a Key Exists Using typeof Operator
- The
typeofoperator 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
makeproperty for thecarobject usingtypeof, which returnsfalse. This happens because the value of themakeproperty is notundefined. - On the other hand, the value of the
yearproperty for thecarobject isundefinedor doesn't exist.
Note:
- Using
typeofmethod, you can only checks forundefinedvalues, not if the property is truly present.- It can be misleading if the property's value is
undefinedas 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
yearproperty exists incarobject, but the value of theyearproperty is undefined. Hencetypeofmethod returns true.- Therefore, it is not recmomended to use the
typeofmethod 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?.keyExample:
const car = { make: 'Toyota', details: { model: 'Corolla' } };
console.log(car.details?.model); // 'Corolla'
console.log(car.details?.year); // undefinedConclusion
In conclusion, there are multiple methods to check if a key exists in JavaScript objects, each suited for different scenarios.
inoperator: Quick and easy, checks prototype chain.hasOwnPropertymethod: Checks only own properties, safer in many contexts.Object.keysmethod: Useful when working with key arrays, more performance-intensive.typeofoperator: Simple check forundefined, but with some limitations.- Checking for
undefined: Direct but doesn't distinguish between non-existent andundefinedvalues. - 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.
