Javascript: Computed Property Names (ES6)

tejesh p
Frontend Weekly
Published in
1 min readDec 26, 2017

Unlike python dictionary, javascript objects need not have quotes around properties.

var eatables = {fruit: 'Apple', vegetable: 'Carrot'}
var edibles = {'fruit': 'Apple', 'vegetable': 'Carrot'}
// both eatables and edibles object return similar objects

What do you do when you want to have your properties take variables?

//This fails to substitute fruit_var with fruit
var fruit_var = 'fruit'
var eatables = {fruit_var: 'Apple', vegetable: 'Carrot'}
console.log(eatables) // {fruit_var: 'Apple', vegetable: 'Carrot'}

One way is to:

var eatables = {vegetable: 'Carrot'}
var fruit_var = 'fruit'
eatables[fruit_var] = 'Apple'
console.log(eatables) // {fruit: 'Apple', vegetable: 'Carrot'}

In ES6, you can use shorthand computed property names.

var fruit_var = 'fruit'
var eatables = {[fruit_var]: 'Apple', vegetable: 'Carrot'}
console.log(eatables) // {fruit: 'Apple', vegetable: 'Carrot'}

Not only that, you can even do javascript computations using computed property names

var eatables = {[fruit_var]: 'Apple', [fruit_var + ' Cake']: 'yummy' }
console.log(eatables) // {fruit: 'Apple', fruit Cake: 'yummy'}

--

--