jskatas.org Continuously Learn JavaScript. Your Way.

Object literal: setter

A setter binds an object property to a function to be called when there is an attempt to set that property.

An object literal can also contain setters

defining: a setter

by prefixing the property with set (and make it a function)
let theX = null; const obj = { x(newX) { theX = newX; } }; obj.x = 'the new X'; assert.equal(theX, 'the new X');
must have exactly one parameter
let setterCalledWith = void 0; const obj = { x() { // <<<<=== it's not a setter yet! if (arguments.length === 1) { setterCalledWith = arguments[0]; } } }; assert.equal(obj.x = 'new value', setterCalledWith);
can be a computed property (an expression enclosed in [])
const publicPropertyName = 'x'; const privatePropertyName = '_' + publicPropertyName; const obj = { [privatePropertyName]: null, // write the complete setter to make the assert below pass :) }; obj.x = 'axe'; assert.equal(obj._x, 'axe');

working with/on the setter

you can use delete to remove the property (including it`s setter)
let setterCalled = false; const obj = { set x(param) { setterCalled = true; } }; // delete the property x here, to make the test pass obj.x = true; assert.equal(setterCalled, false);


Description of all the details of a setter.
"An accessor property associates a key value with one or two accessor functions ..."
The syntax definition of how to write an (accessor) method.
Announcement of this kata on twitter.

Required Knowledge

Related Katas

Global Object API

Object API

Object literal

Difficulty Level


First Published

28 July 2015


4 tests to solve