Today I learnt that in Javascript, Typescript or Node, object-destructuring default-values can be function-calls

Image of the code example pasted into a Javascript console

This learning assumes good knowledge of Destructuring assignment in Javascript, Typescript or Node. See these MDN docs for a foundation in this, particularly Object destructuring and default values.

Today I learnt

  1. A default value can be a function call, e.g. const { foo = f() } = someObjectWhereFooIsOptional
  2. The function is only called if the default value is used. i.e. if the target value is undefined

Here's an example you can copy-paste into your console:

let defaultsGenerated = 0;
const d = (id) => {
defaultsGenerated++;
return `DEFAULT_${id}`;
};
const { foo = d("A"), bar = d("B") } = { foo: "hello", bar: null };
console.log(foo); // 'hello'
console.log(bar); // 'DEFAULT_B'
console.log(defaultsGenerated); // 1

Credit to Daniel Bird who just did this naturally while we were pairing, which made me 🤔



Spotted a typo? Edit on Github


Unless otherwise stated I am the creator of all the text, images and code.

Generally I'm happy to share but let's talk first if you want to license or commercialise any of it

© 2022 Laurence Lord