Skip to content

Instantly share code, notes, and snippets.

@abstractmachines
Last active December 31, 2020 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abstractmachines/4c9e933c4f145e8f434f200af2457fc3 to your computer and use it in GitHub Desktop.
Save abstractmachines/4c9e933c4f145e8f434f200af2457fc3 to your computer and use it in GitHub Desktop.
Functional Programming: Optionals, Maybes, and Optional Chaining and Nullish Coalescing

WIP

Optional chaining, null coalescing, and optionals and maybes

The maybe/optional data types in functional languages such as Haskell and Scala have ways to handle null/undefined that are often superior to using validation, conditionals and operators to infer whether or not a value is nullish.

That's what optional chaining and null coalescing remind me of. They're also a replacement for usage of Lodash .get() method which allows for default values to be set in the last parameter, hence handling nullish value use cases.

Optional chaining

Rather than using something.property.anotherproperty, which can error (and hence crash your program/web page) if it encounters a nullish value for one of the properties, we use something?.property?.anotherproperty instead, which only returns undefined (instead of an error) if a nullish value is encountered in one of the properties.

Nullish Coalescing

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

Usage:

Article on compatibility/proposal stage: https://stackoverflow.com/questions/59574047/how-to-use-optional-chaining-in-node-js-12

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment