You're comparing 2 different things
In your context, in
operator is similar to Object.hasOwnProperty
, and its returned value is true/false.
const address = {
zipCode: 123
}
console.log('zipCode' in address) //true
console.log(address.hasOwnProperty('zipCode')) //true
Optional chaining is to check undefined values optionally
//the short form of `address && address.zipCode`
console.log(address?.zipCode) //false - because no `address` variable
You can consider this case that zipCode
property is there but its value is undefined
const address = {
zipCode: undefined
}
console.log('zipCode' in address) //true
console.log(address?.zipCode) //undefined!
From the above example, you can see that zipCode
is in address
, but optional chaining does not help you to check it but returns its value instead.
what is the benefit of using in
keywords instead of Optional Chaining
?
In the conclusion, you should use in
when you want to check properties in that object exist or not. In other cases, you can use optional chaining to not only verify property availability but also its values (0
, null
, and undefined
).