Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript re-assign let variable with destructuring [duplicate]

In my React app I am using airbnb's eslint style guide which will throw an error if I do not use destructuing.

In the situation below, I first use let to assign the two variables latitude and longitude to the coordinates of the first item in an array of location objects. Then I try to use destructuring to re-assign their values if the user has given me access to their location.

let latitude = locations[0].coordinates[1]; let longitude = locations[0].coordinates[0];  if (props.userLocation.coords) {   // doesn't work - unexpected token   { latitude, longitude } = props.userLocation.coords;    // causes linting errors   // latitude = props.userLocation.coords.latitude;   // longitude = props.userLocation.coords.longitude; } 

Destructuring inside the if statement causes an unexpected token error.

Re-assigning the variables the old fashioned way causes an ESlint: Use object destructuring error.

like image 519
Phil Mok Avatar asked Feb 09 '18 21:02

Phil Mok


People also ask

How do you swap variables using Destructuring assignment?

[a, b] = [b, a] is the destructuring assignment that swaps the variables a and b . At the first step, on the right side of the destructuring, a temporary array [b, a] (which evaluates to [2, 1] ) is created. Then the destructuring of the temporary array occurs: [a, b] = [2, 1] .

Can you Destructure a function in JavaScript?

The object destructuring is a useful JavaScript feature to extract properties from objects and bind them to variables. What's better, object destructuring can extract multiple properties in one statement, can access properties from nested objects, and can set a default value if the property doesn't exist.

Does Destructuring copy reference?

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables. If this data happens to be an object reference, this object reference will be copied into the new variable, or in your case constant.

How do you're assign variable in JavaScript?

In JavaScript, we can simply reassign the new value to the variable. When we change the value of a variable, we do not use var again. We simply use the = to give the variable a new value.


1 Answers

 ({ latitude, longitude } = props.userLocation.coords); 

Destructuring needs to be either after a let, const or var declaration or it needs to be in an expression context to distinguish it from a block statement.

like image 138
Jonas Wilms Avatar answered Sep 21 '22 10:09

Jonas Wilms