De-Constructicon by any other name
By: Brad
Hey Brad I was using Object Destruction but I already have a variable in my scope with the same name as the object property how can I deal with this collision?
Ah yes the fact that when destructing an object the local variable which holds the value of the property plucked off the object will by default be the same name as the object property does mean that you need to watch how you name other local variables… or does it?
Destructuring
For those unfamiliar with destructuring it is a new feature in ES2015 which lets you decompose an object and pluck out a property from the object.
const myObject = { hello: 'world' }; const { hello } = myObject; console.log(`hello ${hello}`); // prints hello world
In the above we take the object myObject
which has a property called hello
and destruct it to just pull out the hello
property and store it in a const variable named hello
. This way we can access the hello property without needing a reference to the parent object.
Property Alias
You can rename the local variable created during the destruction by providing an alias.
function getPeople() { return { firstName: 'Esther', lastName: 'Lee' }; } const { firstName: fName, lastName: lName } = getPeople(); console.log('firstName: ' + fName); console.log('lastName: ' + lName);
With the above I can deconstruct the object returned from getPeople()
into two variables.
I can also rename the variables with an alias so instead of having to use the property names given (firstName, lastName) I can assign the values to names of my own choosing; in this case fName and lName.
So yes you can handle naming collisions when destructing via property alias. To see a live demo check out my Runkit Note Book
Until next time think imaginatively and design creatively