Making parameters required

JavaScript

Functions in JavaScript don’t have “required” parameters. We can emulate them by setting a function that throws an error as a parameter’s default value. This assigned function call only happens if we omit the parameter, making it required.

// This function takes a parameter, but it can also be called without one.
const askAbout = thing => `What’s your favorite ${thing}?`

askAbout('color')  // ⇒ "What’s your favorite color?"
askAbout()         // ⇒ "What’s your favorite undefined?" ← not ideal

// We can pass a function as the parameter’s default value that always
// throws an error. It only gets called when we don’t pass a value for
// that parameter.
const throwIfMissing = () => { throw new Error(`Missing parameter!`) }
const askAbout = (thing = throwIfMissing()) => `What’s your favorite ${thing}?`

askAbout('color')  // ⇒ "What’s your favorite color?"
askAbout()         // Error: Missing parameter! ← we want this

More fire tips

Read all fire tips →