Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript ES6 spread operator on undefined [duplicate]

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?

like image 359
omri_saadon Avatar asked Oct 26 '17 14:10

omri_saadon


People also ask

Does spread operator ignore undefined?

As you can see, no errors - the object-spread operator safely ignored the null and undefined argument, leaving us with a working clone of the target.

Can we spread undefined?

So the answer is: null and undefined values are just fine when spreading on a React element.

Does spread operator do deep clone?

For nested objects the spread operator will provide a deep copy to the first instance of the values but leaves all the nested data as shallow copies sharing a space in memory with original.

How does the spread operator work in ES6?

JavaScript ES6 (ECMAScript 6) introduced the spread operator. The syntax is three dots(...) followed by the array (or iterable*). It expands the array into individual elements. So, it can be used to expand the array in a places where zero or more elements are expected.


1 Answers

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

like image 65
strider Avatar answered Oct 06 '22 23:10

strider