DEV Community

Cover image for Why { ...defaultValues, ...newValues } can hide a bug

Why { ...defaultValues, ...newValues } can hide a bug

Guilherme Moraes on March 22, 2024

Using the spread operator to create a new object using other objects is not unusual, but what happens if both objects have the same key? TL;DR: T...
Collapse
 
kiliman profile image
Kiliman

Hmm.. interesting. Typically, I only want to override the defaults if the new value is undefined (not included in the object). If I only rely on truthy values, then I can't override a default value that is true with false for example.

Anyway, this is definitely helpful to understand so you're not surprised by the behavior.

Collapse
 
best_codes profile image
BestCodes

Informative article, thanks for writing!

Collapse
 
geoffswift profile image
Geoff Swift

nullish coalesce would seem appropriate here. Like this...

fruit: newValues.fruit ?? defaultValues.fruit

Collapse
 
guimoraes profile image
Guilherme Moraes

Yes, it's a great addition, and can prevent issues with falsy values, like numbers of false statement