Javascript: Computed Property Names (ES6)

tejesh p
tejesh p
Dec 26, 2017 · 1 min read

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'}

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

tejesh p

Written by

tejesh p

data dragon

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co