JavaScriptFundamental (ES6), part 1
Shorthand properties and methods in JavaScript
33 Shorthand properties, methods and accessors
easyBuild an object from variables of the same name without repeating yourself, add a method with the shorthand form, and add a getter and setter pair. Then serialise the result and account for what survives.
Stuck? Three hints, smallest first
- 1.
{ code, owner }is{ code: code, owner: owner }. - 2.
{ describe() {} }is the method shorthand, and itsnamecomes from the key. - 3.
JSON.stringifyskips function values, but a getter is an ordinary enumerable property, so it is read.
const code = 'A1';
const owner = 'Ngozi';
const rentNgn = 12000;
const stall = { code, owner }; // shorthand
const till = {
rentNgn,
describe() { return `rent ${this.rentNgn}`; },
get doubled() { return this.rentNgn * 2; },
set doubled(value) { this.rentNgn = value / 2; },
};
const meter = {
rentNgn: 12000,
get doubled() { return this.rentNgn * 2; },
set doubled(value) { this.rentNgn = value / 2; },
};
meter.doubled = 30000; // the setter runs
console.log('shorthand :', stall);
console.log('method :', till.describe(), '| named', till.describe.name);
console.log('getter :', till.doubled);
console.log('setter ran :', meter.rentNgn);
console.log('serialised :', JSON.stringify(till), '<- method gone, getter called');
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('shorthand takes the key from the variable name', stall, { code: 'A1', owner: 'Ngozi' });
test('and keys appear in the order written', Object.keys(stall), ['code', 'owner']);
test('a method shorthand is a function named after its key', till.describe.name, 'describe');
test('and it can use this', till.describe(), 'rent 12000');
test('a getter is read like a plain property', till.doubled, 24000);
test('though it is an accessor, not a value', typeof Object.getOwnPropertyDescriptor(till, 'doubled').get, 'function');
test('and the matching setter runs on assignment', meter.rentNgn, 15000);
test('JSON drops the method and calls the getter', JSON.stringify(till), '{"rentNgn":12000,"doubled":24000}');
Shorthand is what makes a factory read cleanly: const make = (code, owner) => ({ code, owner }) says everything twice fewer times. It also pairs with destructuring — const { code } = stall and { code } are the same notation used to take apart and to put together.
The serialisation assertion is the one that catches people. A method vanishes from JSON silently, which is usually fine, but a getter is invoked and its result is stored — so an expensive or side-effecting getter runs every time something logs the object. If a property should not be serialised, define it with enumerable: false rather than trusting that it looks like a function.