Javascript notes - Part 5 - Computed property names

Javascript notes - Part 5 - Computed property names

Another beautiful syntactical sugar introduced in ES2015

Table of contents

No heading

No headings in the article.

If you have written javascript for a few weeks at least, You might have come across the issue of using a variable value as the key for an object, see the example below.

// Wrong code
function setObject(key, value) {
  return {
    key: value
  }
}

console.log(setObject("name", "Shanu")); // { key: Shanu }
// Correct code
function setObject(key, value) {
  obj = {}
  obj[key] = value
  return obj
}

console.log(setObject("name", "Shanu")); // { name: Shanu }

Computed properties syntax

// Using computed properties syntax
// notice the [ ] around key
function setObject(key, value) {
  return {
    [key]: value
  }
}

console.log(setObject("name", "Shanu")); // { name: Shanu }