Aliases with JavaScript Destructuring
Destructuring in JavaScript has totally changed the way JavaScript is written these days; code is more concise to write but but, from a visual standpoint, the syntax of the language has changed so much. Any good developer knows, however, that change is the constant we live in.
The basic idea behind destructuring in object literals is as follows:
const obj = { x: 1 };
// Grabs obj.x as { x }
const { x } = obj;
There are cases where you want the destructured variable to have a different name than the property name; in that case, you'll use a : newName
to specify a name for the variable:
// Grabs obj.x as as { otherName }
const { x: otherName } = obj;
The syntax for specifying an alternate destructured name for an object property is simple and needed. Destructuring had the capability to confuse developers, especially array destructuring and function argument destructuring, but this alias syntax is a simple trick to keep in your locker!
One of the web components I've always loved has been Facebook's modal dialog. This "lightbox" isn't like others: no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much." With Facebook's dialog in mind, I've created LightFace: a Facebook lightbox...
My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...
If you follow me on Twitter, you saw me rage about trying to make position: absolute
work within a TD
element or display: table-cell
element. Chrome? Check. Internet Explorer? Check. Firefox? Ugh, FML. I tinkered in the console...and cussed. I did some researched...and I...
Image reflection is a great way to subtly spice up an image. The first method of creating these reflections was baking them right into the images themselves. Within the past few years, we've introduced JavaScript strategies and CANVAS alternatives to achieve image reflections without...
Always have to check your site first to see any updates. Love it david. That’s where good developers stand out. Always adapting to new changes. Just trying to get hang of destructing as i’m not the smartest one in the room.
Hello. I’m using an alias for my destructed object property. How can I handle the property when it’s undefined?
Thanks.
I was looking for something like this. I wonder why the proposal for this feature didn’t follow the syntax of import statements.
Example:
this is the typescript syntax
I don’t know why people call it an “alias”. If it were an alias, changing the variable would change the object property. E.g.
I think the only time you can have an alias in JavaScript is with reference types.
When destructuring we use the word “alias” to refer to a differently named variable with the same value, rather than a different name that should reference the same variable.