Below is an extract from MDN example
var d = withValue.d || (
withValue.d = {
enumerable: false,
writable: false,
configurable: false,
value: value
}
);
Is this a safe way to check if a property exist else assign and initialize it ? If not is there a better, safe and optimized way?
No, it's not safe, because the property may indeed exist on the object but be falsey, in which case the withValue.d ||
would fail and go onto the alternation, assigning an object to the d
property despite the fact that the d
property already exists. Use hasOwnProperty
instead, and don't put an assignment where an expression is expected:
if (!withValue.hasOwnProperty('d')) {
withValue.d = {
enumerable: false,
writable: false,
configurable: false,
value: value
}
}
const { d } = withValue;
If the d
property, if it exists, will always be an object, then your original code will work, because objects are always truthy. (Code is still somewhat smelly though, due to the assignment-as-expression)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments