liveBook · Manning

getOrElse

As explained in Functional Programming in JavaScript

An operation that returns the wrapped value when present or a default value otherwise.

getOrElse returns the wrapped value when it exists, and a default value when it does not. It is used with Maybe-style values to avoid scattered null checks and to supply a safe fallback at the end of a chain. section 5.3

A common pattern is to map through several fields and finish with getOrElse. That keeps the missing-value handling in one place instead of branching at every step. section 5.3

Fallback after a lookup chain

A student lookup can be mapped to firstname for display, then finished with getOrElse('Enter first name'). A country lookup can map school, address, and country before returning 'Country does not exist!'.

Typical uses shown here include:

  • displaying a form field value or a placeholder when no data is available. section 5.3

How Functional Programming in JavaScript covers it

How deep it goes
Explains the operation at the definition-and-example level, then shows it in chained property lookups without detailing internals.
Examples
Uses student username display, form field defaults, and a nested school-address-country lookup.
What it assumes
Assumes basic familiarity with Maybe-style wrapped values and map chains, then introduces the fallback behavior from scratch.
What you can do after
Apply it to return a default value when a Maybe chain has no wrapped result.
How it connects
Connects Maybe, Just, Nothing, map, and null-checking patterns.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.