DEV Community

Discussion on: JavaScript check if property exists in Object

Collapse
 
supportic profile image
Supportic • Edited

You could also do if(userOne["email"]) but I would not recommend to check like this userOne.email !== undefined because what if the object in general does not exist?

if ({} !== undefined) true
=> true

if (undefined !== undefined) true
=> undefined
Enter fullscreen mode Exit fullscreen mode

means:
When userOne does not exist e.g. you forget to pass parameter in a function call, then (undefined).email !== undefined will evaluate not into false or true

undefined && true
=> undefined
undefined && false
=> undefined
Enter fullscreen mode Exit fullscreen mode

=> skip if condition

A fix for that though would be to check if the object exist and if not, assign an empty object to it.
options = options ?? {}
if (options.switch !== undefined) can now resolve in true or false.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Yeah that's why I mentioned the undefined check to be the least favorite one of all.
It get's messy and very prone to cause headaches later on.

Collapse
 
peerreynders profile image
peerreynders

what if the object in general does not exist?

As suggested in another comment optional chaining will work just fine here.

const options = undefined;
console.log(options?.email ? true : false); // false
// i.e. No Uncaught ReferenceError 
// even though options is `undefined`
Enter fullscreen mode Exit fullscreen mode