quedemy-logo
check-if-key-exist-in-javascript

Check If Key Exists in Javascript

May 24, 2024 · 9 min read

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. The in operator returns true 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 the person 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. 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')); // 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 the car object. So the hasOwnProperty method returns true.
  • On the other hand toString method is inherited from Object.prototype. Hence, the hasOwnProperty method returns false

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 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')); // true
  • In the above code block, you use the Object.keys method to create an array of keys and assign it to the variable arrayOfCarProperty.
  • Then, you use the includes method that returns true because the make property exists in the arrayOfCarProperty 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 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'); // true
  • In the code block above, you are checking the value of the make property for the car object using typeof, which returns false. This happens because the value of the make property is not undefined.
  • On the other hand, the value of the year property for the car object is undefined or doesn't exist.

Note:

  • Using typeof method, you can only checks for undefined 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 in car object, but the value of the year property is undefined. Hence typeof 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 for undefined, but with some limitations.
  • Checking for undefined: Direct but doesn't distinguish between non-existent and undefined 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.

quedemy-logo

© 2024 Quedemy. All rights reserved

LinkedIn

Company

About usBlogContact usSitemap