Skip to main content


Assign properties in a constructor’s parameter object (with defaults) to object being instantiated in JavaScript

https://codeberg.org/aral/gists/src/branch/main/assign-properties-in-a-constructors-parameter-object-with-defaults-to-object-being-instantiated-in-JavaScript.md

This is a little something I ended up playing around with this morning before figuring out how to do it (after spending far too much time down a rabbit hole with object destructuring when what I really needed was creative use of the spread operator).

(Useful for custom objects in JSDB 5 – https://codeberg.org/small-tech/jsdb#custom-data-types)

#JavaScript #parameterObject #defaults #JSDB

in reply to Aral Balkan

could you expand on why the spread before the default values is required ? I understand the spread for the provided parameters, but I would have expected having the defaults as a plain object would have been enough.
in reply to Zwifi

@Zwifi It’s because we’re creating a new object that initially contains the default properties and then copying over the actual properties from the parameter object.

The inline syntax is confusing to read, however, so I just updated the gist to separate it out into three statements. Also, given that the spread syntax is syntactic sugar for Object.assign() and since we’re using Object.assign() anyway, I added an example that only uses Object.assign(). Hopefully it’s easier to read now :)

in reply to Aral Balkan

@Zwifi Although… if you don’t need to reference `this` in your defaults, you can both simplify all that and get type inference for free by defining your defaults in class fields with initialisers.

(Updated the gist with an example of that: https://codeberg.org/aral/gists/src/branch/main/assign-properties-in-a-constructors-parameter-object-with-defaults-to-object-being-instantiated-in-JavaScript.md#so-is-all-this-really-necessary)