How to properly check if an object property exists in JavaScript (undefined)
Hi everyone! I started learning JavaScript and encountered a confusing situation. I have an object with user data, and I want to check if a certain property exists in it. But I'm confused between `undefined`, `null`, and the property not being declared at all.
Here's an example. Suppose I have an object:
```javascript
const user = {
name: 'Ivan',
age: 25
};
```
I want to check if the user has an `email` property. If I write:
```javascript
if (user.email === undefined) {
console.log('Email not specified');
}
```
This seems to work, but I've heard that doing it this way is incorrect. Why? After all, `user.email` does return `undefined`.
But what if I deliberately set a property with the value `undefined`?
```javascript
const user2 = {
name: 'Maria',
No answers yet.
Log in to leave an answer