Javascript: Assign values to already declared variables using destructuring
A lot of time we get this requirement to assign a variable to a new value which we get from an Array or Object.
Here is the common way to do it:
let platform = "twitter";
let followersCount = 122;
let updated_social_data = {
social_platform: "instagram",
followers_count: 452
};
platform = updated_social_data.social_platform;
followersCount = updated_social_data.followers_count;
But with the ES6 destructuring you can do it in below manner.
updated_social_data = { social_platform: "twitter", followers_count: 3456 };
({ social_platform: platform, followers_count: followersCount } = updated_social_data);
You can also apply this for Array Destructuring too
Top comments (1)
I think the headline isn't correct. Whereas the first example is correct the second is not same.
The second example is slightly different according to the headline, you are creating new variables on the scope.
If they exist the value is overwritten but if they don't exist they are created with the value of the object property.
Some comments have been hidden by the post's author - find out more