jskatas.org Continuously Learn JavaScript. Your Way.

Object literal: computed properties

Object literal properties may be computed values.

Object literal properties may be computed values

a computed property x needs to be surrounded by []
const propertyName = 'x'; const obj = {propertyName: 1}; assert.equal(obj.x, 1);
can also get a function assigned
const key = 'func'; const obj = {[key]: 'seven'}; assert.equal(obj.func(), 'seven');
the key may also be the result of a function call
const getName = () => 'propertyName'; const obj = {[getName]() {return 'seven'}}; assert.equal(obj.propertyName(), 'seven');
the key can also be constructed by an expression
const what = 'Key'; const obj = {['proper' + what]: null}; assert('propertyName' in obj);
accessor keys can be computed names too
const obj = { set ['key'](_) {return 1}, }; assert.equal(obj.key, 1);

Required Knowledge

Related Katas

Global Object API

Object API

Object literal

Difficulty Level


First Published

3 April 2015


5 tests to solve