Conditionally spread into Object/Array - Javascript

Posted on June 11, 2020

There comes a time when we want to add more fields/elements into an array or object when it satisfies a certain condition. This blog is an exploration of how and why.

Spreading into an Array

isWinter is a boolean variable and you need to add winterEssentials if it’s true and nothing otherwise.

We need an empty array at end because we cannot spread undefined or null into an array (they are not iterables). Spreading an empty array into another just keeps the array intact.

const initialArray = ['a', 'b', 'c'];
const resultingArray = [...initialArray, ...[]];
console.log(initialArray, resultingArray); // Have the same elements.

Spreading into an Object

Rest spread into object is a Stage 4 ECMA proposal and is implemented in most browsers.

It mimics the behavior of existing Object.assign operator.

You will notice here that resorting to a conditional operator isn’t necessary. This is because rest spread for objects tries to wrap any primitive it finds to an object.

console.log(null); // {}
console.log(undefined); // {}
console.log(0); // {}
console.log('abc') // {0: "a", 1: "b", 2: "c"}, well an array is also an object

Guide to Type Coercion in JavaScript

So the expression (isHacker && hacker) returns undefined which our spread operator converts to {} and spreading an empty array into an object results in nothing.

That’s conditional spread.


Jithin Sathyansiresquire
Buy me a coffeeBuy me a coffee