Monday, March 7, 2022

optional chaining for safely calling a possibly non-existent function

So optional chaining is relatively new in Javascript, so you can get deeply nested values from a stricture, even if the "branches" above the leaf are missing - like

user?.preferences?.colors

is safe to. call, even if user.preferences doesn't exist, and you don't have to write

user && user.preferences && user.preferences.colors

(or the kind of syntactic ugliness of

const key = 'preferences';
users?.[key]?.colors

 part of my brain says... what's the dot doing there before the square brackets...)

Anyway, turns out you can use that for functions as well - useful even if you aren't chaining per se - you can write

someFunction?.();

And it is safe, even if someFunction is not defined.

As always, I'm not crazy about how new syntaxes increase the cross-section of what folks have to know to read code, and `?.` is a bit ugly but it is definitely more DRY (Don't Repeat Yourself) than 

someFunction && someFunction();

Here's a little codepen I made:

const bar = () => {
  console.log('bar!!');   
}
const baz = undefined;
const foo = () => {
  baz?.();
  bar?.();
}
<button onclick="foo()">foo</button>

You can see, bar is still called even though we try to call baz before, which is undefined.

No comments:

Post a Comment