Avoid Unstructured Errors from Uncertain

Let's 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 good, but what if the point is not defined? Now I get the error message:

"Cannot read property 'x' of undefined" .

So how do I avoid this?

I want to do something like

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

but this is a syntax error.

I can only see that this is an option:

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

Which dummy goes to:

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

Here we create an object to avoid an undefined error. It seems wasteful.

Is there any syntax that I am missing to avoid this? Something that could go into something like this:

 var x, y; if (typeof point !== 'undefined') { x = point.x; y = point.y; } 
+9
source share
3 answers

[...] What if the point is not defined? Now I get the error: "Unable to read property" x "from undefined"

So how do I avoid this?

If you want to write clean code, you can explicitly check this condition:

 let { x, y }; if (typeof point === 'undefined') { x = y = undefined; } else { { x, y } = point; } 
0
source

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

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

One contributor:

 const {x, y} = typeof point !== 'undefined' ? point : {} 

EDIT :

If you avoid the {} that creates the object, use NaN or other primitives, it will return undefined

 const {x, y} = typeof point !== 'undefined' ? point : NaN 
-1
source

Source: https://habr.com/ru/post/1269445/


All Articles