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.
- 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');
}Sw:ecruoww.theitroad.com- Using the inoperator:
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.
