Javascript re-assign let variable with destructuring

JavascriptEcmascript 6Eslint

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

 ({ 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPhil MokView Question on Stackoverflow
Solution 1 - JavascriptJonas WilmsView Answer on Stackoverflow