Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid an error when destructuring from undefined

Lets say I have this code:

const {x, y} = point;

Babel will turn this into:

var _point = point,
    x = _point.x,
    y = _point.y;

Which is fine, but what if point is undefined? Now I get an error:

"Cannot read property 'x' of undefined".

So how do I avoid this?

I want to do something like

const {x, y} = {} = point;

but that's a syntax error.

I can only see that this is an option:

const {x, y} = point || {};

Which babel transpiles to:

var _ref = point || {},
    x = _ref.x,
    y = _ref.y;

Here we're creating an object just to avoid an undefined error. This seems wasteful.

Is there some syntax I'm missing that would avoid this? Something that would transpile to something like this:

var x, y;
if (typeof point !== 'undefined') {
    x = point.x;
    y = point.y;
}
like image 649
Jack Allan Avatar asked Jul 03 '17 13:07

Jack Allan


1 Answers

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                  
like image 87
Jitender Avatar answered Oct 27 '22 01:10

Jitender