JavaScript(JS) JS check if a key exists in an object

To check if a key exists in an object in JavaScript/JS, you can use the hasOwnProperty() method or the in operator.

  1. Using hasOwnProperty() method:
const obj = { 
  key1: 'value1', 
  key2: 'value2', 
  key3: 'value3' 
};

// Check if 'key2' exists in the object
if (obj.hasOwnProperty('key2')) {
  console.log('Key exists in the object');
} else {
  console.log('Key does not exist in the object');
}
S‮w:ecruo‬ww.theitroad.com
  1. Using the in operator:
const obj = { 
  key1: 'value1', 
  key2: 'value2', 
  key3: 'value3' 
};

// Check if 'key2' exists in the object
if ('key2' in obj) {
  console.log('Key exists in the object');
} else {
  console.log('Key does not exist in the object');
}

Both of these methods return a boolean value, true if the key exists in the object and false if it does not.