Computed Property Names in JavaScript

1 min read.

In this video, you’ll learn how to have an expression be computed as a property name on an object in JavaScript using ES6’s (ES2015) “computed property names” feature.



We’re going to cover ES6’s “Computed Property Names” feature. What it allows you to do is it allows you to have an expression be computed as a property name on an object.

Say we had a function called “objectify” which is going to take in a key and a value. Then, it’s going to return a new object with the key being the key on that object and the value obviously being the value. The old way we would have to do this is we would create an object and then we would use bracket notation to set every key in that object equal to the specific value.

function objectify (key, value) {
  let obj = {}
  obj[key] = value
  return obj

The reason we have to do it this way with 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. That’s the whole reason that bracket notation exists.

Now, saw we had the same objectify function that took in a key and a value. With computed property names, instead of having to create an object and then add properties to it using bracket notation, what we can do is return a new object, and using object literal notation, put brackets around the key. Now, whatever the variable represents is going to be added as a property on the object.

function objectify (key, value) {
  return {
    [key] : value

Now both of these functions are essentially identical and if we were to invoke either one of them passing them “tyler” as the key and “27” as the value objectify('tyler', 27), what we would get back is an object which had “tyler” as the key and “27” as the value.

  tyler: 27

Liked this post? Share it 🕺


Listen, I get it, newsletters are the worst.

But, as Louis from Colorado says, "This newsletter sucks less than the others".

We only send spam. That's a joke.