Learn Node.js unit testing with Jest, using mocking, snapshots, and best practices to ensure reliable and efficient application performance.
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.
in Operatorin operator is one of the simplest and most commonly used methods to check if a key exists in a JavaScript object. The in operator returns true if 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); // falsein operator checks both the object properties and its inherited properties. For example:const person = { name: 'John' };
console.log('toString' in person); // truetoString method exists in the prototype chain of the person object.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.
hasOwnProperty MethodhasOwnProperty method is another common way to check the existence of a key in an object. The hasOwnProperty 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')); // falsehasOwnProperty 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')); // falsemake property is directly related to the car object. So the hasOwnProperty method returns true.toString method is inherited from Object.prototype. Hence, the hasOwnProperty method returns falseNote: Using
hasOwnPropertyis a better option when you are not considering checking the inherited properties of an object.
Object.keys and includes Methods to Check If a Key ExistsObject.keys method returns an array of a given object's properties. Just like you do using the for loop. The Object.keys method can also be used to check if a key exists with the help of the includes method.Syntax:
Object.keys(object)Example:
const car = { make: 'Toyota', model: 'Camry' };
const arrayOfCarProperty = Object.keys(car); // ['make', 'model']
console.log(arrayOfCarProperty.includes('make')); // trueObject.keys method to create an array of keys and assign it to the variable arrayOfCarProperty.includes method that returns true because the make property exists in the arrayOfCarProperty array.typeof Operatortypeof operator also helps to check if a key exists by checking if its value is undefined.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'); // truemake property for the car object using typeof, which returns false. This happens because the value of the make property is not undefined.year property for the car object is undefined or 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
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); // undefinedIn 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 for undefined, but with some limitations.undefined: Direct but doesn't distinguish between non-existent and undefined values.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.
