ImaginativeThinking.ca


A developers blog

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

Brad

My interest in computer programming started back in high school and Software Development has remained a hobby of mine ever since. I graduated as a Computer Engineering Technologist and have been working as a Software Developer for many years. I believe that software is crafted; understanding that how it is done is as important as getting it done. I enjoy the aesthetics in crafting elegant solutions to complex problems and revel in the knowledge that my code is maintainable and thus, will have longevity. I hold the designation Certified Technician (C.Tech.) with the Ontario Association of Computer Engineering Technicians and Technologists (OACETT), have been certified as a Professional Scrum Master level 1 (PSM I) and as a Professional Scrum Developer level 1 (PSD I) by Scrum.org as well as designated as an Officially Certified Qt Developer by the Qt Company. For more on my story check out the about page here

Feel free to write a reply or comment.