How to check if an object has a certain property in es6?
In ES6, you can use the Object.prototype.hasOwnProperty() method to check if an object has a specific property. This method will return a boolean value indicating whether the object has the specified property name. For example:
const obj = { name: 'Alice', age: 25 };
console.log(obj.hasOwnProperty('name')); // true
console.log(obj.hasOwnProperty('gender')); // false
In addition, ES6 also introduced the in operator to determine if an object has a specific property. When using the in operator, if the object or its prototype chain contains the specified property, it will return true; otherwise, it will return false. For example:
const obj = { name: 'Alice', age: 25 };
console.log('name' in obj); // true
console.log('gender' in obj); // false
It’s important to note that the ‘in’ operator can determine if an object property exists, including properties in the object’s prototype chain. On the other hand, the hasOwnProperty() method only checks if the object itself has that property.