Javascript ES6 spread operator on undefined

JavascriptEcmascript 6Javascript ObjectsSpread Syntax

Javascript Problem Overview


While developing my react App, I needed to send a conditional prop to a component so I found somewhere a pattern to do so, although it seems really weird to me and I couldn't understand how and why it worked.

If I type:

console.log(...undefined)   // Error 
console.log([...undefined]) // Error
console.log({...undefined}) // Work

When the spread operator is activated on undefined an error is raised, although when the undefined is inside an object, an empty object returned.

I'm quite surprised regarding this behavior, is that really how it supposed to be, can I rely on this and is that a good practice?

Javascript Solutions


Solution 1 - Javascript

This behavior is useful for doing something like optional spreading:

function foo(options) {
  const bar = {
    baz: 1, 
    ...(options && options.bar) // options and bar can be undefined
  } 
}

And it gets even better with optional chaining, which is in Stage 4 now (and already available in TypeScript 3.7+):

function foo(options) {
  const bar = {
    baz: 1, 
    ...options?.bar //options and bar can be undefined
  } 
}

a thought: its too bad it doesn't also work for spreading into an array

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionomri_saadonView Question on Stackoverflow
Solution 1 - JavascriptstriderView Answer on Stackoverflow