Skip to content Skip to sidebar Skip to footer

Can Someone Explain This Seemingly Weird Assignment `{key=value} = Argument`

Context: this is a task in a javascript tutorial. The code is supposed to generate a subclass ExtendedClock of Clock that allows the console to show the current time in a customize

Solution 1:

That's object destructuring syntax with a default value. If the object you're destructuring contains a precision key, that value will be used, but if it does not, 1000 will be used.

If the key exists, its value will be used:

const options = { precision: 800 };
const { precision = 1000 } = options;
console.log(precision); // logs 800

but if the key does not exist, the default value will be used:

const options = {};
const { precision = 1000 } = options;
console.log(precision); // logs 1000

Your code probably doesn't work because when you call super.start(), the superclass starts a loop with

setInterval(() =>this._render(), 1000);

Your code starts a loop after this is called, but both loops are now running, causing the render function to be called every 1000ms by the superclass's setInterval, and then also separately every precisionms by your subclass's loop.

Instead of calling super.start() at the beginning of your loop, try just calling this._render().

Solution 2:

this weird code is just a handy way to overwrite the default value if there is a Property for it.

let options = { precision: 999, template: 'h:m:s' };
let { precision = 1000 } = options; // precision === 999let options = { template: 'h:m:s' };
let { precision = 1000 } = options; // precision === 1000

For the second issue I would need some more input. Which error do you get?

Post a Comment for "Can Someone Explain This Seemingly Weird Assignment `{key=value} = Argument`"