Is this a safe way to check if a property exist else assign one?

Vishakh PC

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?

CertainPerformance

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.

edited at
0

Comments

0 comments
Login to comment

Related

Safe way to check if a property of an object contains a substring

JavaScript check if one object property value is exist on another object property

Better way to check if row exist update else insert new record

Is there any safe way to check the deep of object's property?

Typescript check if property exist

Check if the property exist in array

Laravel check property exist

Cannot assign property "FontFamily": Property does not exist

Safe way to extract property names

Mongoose findById check if property exist

Check if object exist and has property

Property 'assign' does not exist on type 'ObjectConstructor'

Fastest way to check if row exist

Assign one property to child of a class

How would you check if property name(s) from one object exist in another?

check if variable exist using if else bash script

Safe way to check if array element exists?

How to simplify check if property exist in TypeScript?

Property does not exist on type after type check

check if property value exist before push item

How to check if a value/property exist in JSON data

Is there a way to check if a property has a setter?

Is there a way in LESS to remove a property if a variable does not exist?

More elegant way to assign optionals to a lazy property

Is there a way to assign a dynamic resource to a dependency property in code

Is there a way to assign a custom object property to an element?

Good way to assign property with extension method

How to check in neat way if collection contains an object which's one property is equal to the object passed to Contains method?

LINQy way to check if any objects in a more than one collection have the same property value