I often saw in operator in some library of Javascript.
but I think in operator has risk of causing human errors.
because we have to write property name as string type.
I think optional chaining could be alternative of in operator and It looks more safe.
we can get help of intelligence of IDE during writing code.
what is the benefit of using in keywords instead of Optional Chaining?
AFAIK, in is used to get to know whether the property exists in an object or its prototype or not.
const address = {
zipCode: 1234,
country: 'usa',
city: 'new York',
};
if ('zipCode' in address) {
console.log('This is address from in checking');
}
and if you are using optional chaining then you are checking the value to be truthy or not
const address = {
zipCode: 1234,
country: 'usa',
city: 'new York',
};
if (address?.zipCode) {
console.log('This is address from optional chaining');
}
But think of a situation where the value of that property is a falsy value then the in operator will give you the result of property existence. If the value is a falsy value then you have to make additional checks to know whether the property exists or not.
Value can be anything so you have to make necessary checks in
optional chaining
const address = {
zipCode: 0,
country: 'usa',
city: 'new York',
};
if ('zipCode' in address) {
console.log('This is address from in checking');
}
if (address?.zipCode) { // Won't work
console.log('This is address from optional chaining');
}
if (address?.zipCode || address?.zipCode === 0) { // Will work with extra checks
console.log('This is address from optional chaining');
}
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
inkeywords instead ofOptional 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).