How to check if a key exists in a JavaScript object

Last updated on May 26, 2021 by Suraj Sharma



In this tutorial, you’ll learn 2 ways to check if a key or property exists in given JavaScript object.


1. Using in operator


You can use the in operator in javascript to check if a key exists in a given object.

Example

const obj = {
  a: 1,
  b: 2
};

console.log('a' in obj); // true
console.log('c' in obj); // false

The in operator returns true if the key to the left of it is present in the object right to it in the expression, otherwise it returns false.

Expression

'key' in object


2. Using Object.hasOwnProperty


The Object.hasOwnProperty() method can be used to check the immediate property of the object, i.e. the property not inherited from its parent object.

The hasOwnProperty method always returns a boolean value.

Example

const obj = {
  a: 1,
  b: 2
};

console.log(obj.hasOwnProperty('c')) // false
console.log(obj.hasOwnProperty('b')) // true


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.