117

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.

Phil Mok
  • 3,452
  • 5
  • 20
  • 34

1 Answers1

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

Jonas Wilms
  • 120,546
  • 16
  • 121
  • 140
  • 14
    Never see that before, thx – Laurent Oct 31 '19 at 20:37
  • 1
    This is lush, great for clean `try catch` blocks, where the function returns an object. – Davey Mar 31 '21 at 09:51
  • 2
    If you are using modern JS and usually elide the semicolons, in this case you must have a semicolon preceding the statement or at the end of the preceding line. Otherwise, the parenthesize expression will be interpreted as a function call on the rvalue of the preceding line. – mrflip Jan 17 '22 at 16:10
  • Saw this first in Node's repo https://github.com/nodejs/node/blob/master/lib/internal/crypto/pbkdf2.js#L42 Thanks for explaining! – obzenner Jan 17 '22 at 20:58
  • MDN docs : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring – Thanh Trung Feb 05 '22 at 14:44