r/javascript • • Apr 28 '19

7 Useful JavaScript Tricks

https://davidwalsh.name/javascript-tricks
505 Upvotes

36 comments sorted by

View all comments

16

u/erfling Apr 28 '19

These are pretty cool.

I was unaware of the aliasing feature for destructured objects. As a TS user, it's confusing. I wish you could us "as"

8

u/darrenturn90 Apr 28 '19

It does seem inconsistent especially when you use as in what is essentially destructuring an import / export ie {default as foo}

Another thing to keep in mind also you can use [value] in destructuring to get the key referred to in the value variable from the destructured object

1

u/AwesomeInPerson Apr 28 '19

Another thing to keep in mind also you can use [value] in destructuring to get the key referred to in the value variable from the destructured object

Could you elaborate / give an example? Didn't fully understand it but sounds interesting :)

3

u/darrenturn90 Apr 28 '19

Say you had const foo = “two”

And you had an object {two: “hello”}

You can const {[foo]: bar} = with that object

3

u/AwesomeInPerson Apr 28 '19

Aaah I see – I tried using computed property names while destructuring before, but it never worked because I tried it without assigning to an alias. (so just const { [foo] } = bar; – makes sense that this doesn't work now that I think about it)

Very nice to know that it works when using an alias, thanks!