My new favourite thing in JS is Nullish coalescing:
The nullish coalescing operator (
??) is a logical operator that returns its right-hand side operand when its left-hand side operand is
undefined, and otherwise returns its left-hand side operand.
return this.thing1 ?? this.thing2 ?? 'default'
Also works well with the Optional Chaining Operator, which is also great - not more “Uncaught TypeError: Cannot read property ‘thing1’ of undefined”:
return this?.things.?.thing1 ?? this?.things?.['thing2'] ?? 'default'
This is like logical or -
|| - but instead of testing for
falsy, it tests for
nullish - which is often what you want.
Nullish all the things!