Advertisement
728x90
You can check whether a key exists in an object or not using three approaches,
1. Using in operator: You can use the in operator whether a key exists in an object or not
javascript
1"key" in obj;and If you want to check if a key doesn't exist, remember to use parenthesis,
javascript
1!("key" in obj);2. Using hasOwnProperty method: You can use hasOwnProperty to particularly test for properties of the object instance (and not inherited properties)
javascript
1obj.hasOwnProperty("key"); // true3. Using undefined comparison: If you access a non-existing property from an object, the result is undefined. Let’s compare the properties against undefined to determine the existence of the property.
javascript
1const user = {
2 name: "John",
3 };
4
5 console.log(user.name !== undefined); // true
6 console.log(user.nickName !== undefined); // falseAdvertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 42
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
126of476