Javascript ES6 spread operator on undefined [duplicate]

删除回忆录丶 提交于 2019-12-04 15:26:39

问题


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?


回答1:


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-1:

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



来源:https://stackoverflow.com/questions/46957194/javascript-es6-spread-operator-on-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!