Back to Homepage
Thursday 4 April 2024
9

How to check if a key exists in an object in javascript

Working with objects is a common and essential task in JavaScript. One of the most frequent operations is checking if a specific key exists within an object. This article explores various ways to perform this check.

Using the 'in' Operator

The 'in' operator is one of the simplest and most straightforward methods to check if an object contains a certain key. The syntax is 'key in object'.

const object = { key: 'value' };
console.log('key' in object); // returns true

Method hasOwnProperty

The 'hasOwnProperty' method provided by JavaScript objects allows to check if the object has a specific property or key as a direct, non-inherited property.

const object = { key: 'value' };
console.log(object.hasOwnProperty('key')); // returns true

Checking Using Undefined

Another way is to check if the value of the key is different from 'undefined'. This technique is useful when it's known that the stored values are not 'undefined'.

const object = { key: 'value' };
console.log(object['key'] !== undefined); // returns true
Share:
Created by:
Author photo

Jorge García

Fullstack developer