Avoid an error when destructuring from undefined

a 夏天 提交于 2019-12-05 03:39:04

To handle undefined error in ES6 object destructuring, you can do something like following

const {x, y} = {...point};
console.log(x)      // undefined                  
console.log(y)      // undefined                  

[…] what if point is undefined? Now I get an error: "Cannot read property 'x' of undefined"

So how do I avoid this?

If you want to write clear code, you can explicitly check that condition:

let { x, y };
if (typeof point === 'undefined') {
    x = y = undefined;
} else {
    { x, y } = point;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!