Destructuring is just a nice way to unpack properties from objects and arrays and assign them to variables. As the trasnpiled code in the question suggests, any kind of operation is not possible.
One hack would be to create 2 more variables (which don’t exist in input
) and set the default value to the number equivalent of the previously destrucutred properties:
let input = { latitude: "17.0009", longitude: "82.2108" }
let { latitude, longitude, lat = +latitude, long = +longitude } = input
console.log(typeof latitude, typeof longitude, typeof lat, typeof long)
The code approximately trasnpliles to this (Babel):
var latitude = input.latitude,
longitude = input.longitude,
lat = input.lat === undefined ? +latitude : input.lat,
long = input.long === undefined ? +longitude : input.long;
It’s just exploiting the order in which the variables are created and assigned property values. Again, this works only if there are no lat
or long
properties in input
. Otherwise, it will fail the ternary condition and lat
will be set to input.lat
.
Something like this would be much easier to read though:
let { latitude, longitude } = input;
let lat = +latitude,
long = +longitude;
OR
let [ lat, long ] = [ +latitude, +longitude ]