Shanu Khera
Notes by Shanu Khera

Notes by Shanu Khera

Javascript notes - Part 5 - Computed property names

Javascript notes - Part 5 - Computed property names

Another beautiful syntactical sugar introduced in ES2015

Shanu Khera's photo
Shanu Khera
·Feb 20, 2021·

1 min read

Play this 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 }
 
Share this