| by Kenneth Chase | 6 comments

Computed Property Names in JavaScript | ES6 | ES2015

In this video, we are going to cover ES6’s computed
property names. Basically what it allows you to do is it allows
you to have an expression be computed as a property name on an object. So let’s go ahead and take a look at an example. So say we had a function and we are going
to call it “objectify” and what it is going to do is it is going to take in a key and
it also is going to take in a value. And then what it is going to do is it is going
to return a new object with the key being the key on that object and the value obviously
being the value. So the old way we would have to do this is
we would have to create an object, and then what we would do is we would use bracket notation
to set every key in that object equal to the specific value and then we would return the
object itself. The reason we have to do it this way where
we create an object and then we use bracket notation is because with ES5 if we had a variable
that we wanted to be a property name on the object we would have to use bracket notation
and that’s the whole reason that bracket notation exists. But with computed property names, what we
can do is say we have the same function that took in a key and a value now instead of having
to create an object and then add properties to it, with bracket notation what we can do
is we can just return a new object. So we are going to use object literal notation here
and then by putting brackets around the key, whatever the variable represents is going
to be added as a property on this object. Now both of these functions are essentially
identical and if we were to invoke either one of them, say we passed it “tyler” as the
key and “27” as the value. What we would get back is an object which
had “tyler” as the key and “27” as the value.



Jun 6, 2018, 11:23 am Reply


Juriy Bura

Aug 8, 2018, 2:36 pm Reply

I'm also teaching JS and I am struggling to find any kind of real-life use-case for this syntax. Your example is very nice, but still a bit artificial. Do you know any real practical cases, when this syntax is useful?

Maggie Wang

Jun 6, 2019, 4:25 pm Reply

this is a great explanation thx


Jun 6, 2019, 1:27 pm Reply

How do you know what the name of your variable / let is in the second example (since in the first you know it's "obj")? Or is that shorter way of writing meant to only be used if you will not use the variable somewhere else?

Tyler McGinnis

Aug 8, 2019, 7:08 pm Reply

🚀 Try our new 2019 React Course – https://tylermcginnis.com/courses/react/?s=youtube-computed-property-names-es6


Oct 10, 2019, 1:48 am Reply

dude ! i really love the end when all the code gets covered by your advert's. had to pause and rewind a couple times

Leave a Reply