Want to create a new #JavaScript object with an optional property


Want to create a new #JavaScript object with an optional property?

Use spread (...) with the logical and operator (&&).

const user = {
name: 'Cory',
...(includeEmail && { email: email })
};

If includeEmail is true, the email property is applied. 😎
A final tweak: Use object shorthand to simplify.

const user = {
name: 'Cory',
...(includeEmail && { email })
};

The right-hand side can be omitted when the left-hand side uses the same identifier.
I use this technique in React with useReducer and Redux reducers.

Here's why:
In reducers, I want to avoid needlessly cloning objects. Each cloned object causes a re-render.

So I use this technique to only clone the properties that need updated.

View original on X