Making function parameters required

Posted on

JavaScript does not natively have a concept of “required” parameters in functions. If we don’t pass a value for a parameter, it will be undefined in the body of that function.

We can emulate required parameters by using a function that throws an error as that parameter’s default value.

If we pass a value for that parameter, we get the expected behavior in the body of the function. The default value only kicks in when we don’t pass a value. The helper function gets called and throws its error if that happens, effectively making the parameter required.

// This function’s parameter is optional.
const love = (thing) => `I love ${thing}!`
 
// We get expected behavior when passing a value to it.
love("pizza")  // ⇒ "I love pizza!"
 
// If we don’t pass a value, it will be `undefined`.
love()         // ⇒ "I love undefined!" ← not ideal
 
// We can make a parameter pseudo-required with a little
// trick using default values for parameters.
 
// This helper ALWAYS throws an error.
const throw = () => {
  throw new Error("Missing thing!")
}
 
// On its own, this function isn’t super helpful.
throw()  // Error: Missing thing!
 
// By using the helper as a parameter’s default value,
// it only gets called when that parameter is missing.
const love = (thing = throw()) => `I love ${thing}!`
 
// Nothing changes in the regular case.
love("pizza")  // ⇒ "I love pizza!"
 
// The helper function throws an error if we don’t pass
// a value, effectively making the parameter required.
love()         // Error: Missing thing! ← better
// This function’s parameter is optional.
const love = (thing) => `I love ${thing}!`
 
// We get expected behavior when passing a value to it.
love("pizza")  // ⇒ "I love pizza!"
 
// If we don’t pass a value, it will be `undefined`.
love()         // ⇒ "I love undefined!" ← not ideal
 
// We can make a parameter pseudo-required with a little
// trick using default values for parameters.
 
// This helper ALWAYS throws an error.
const throw = () => {
  throw new Error("Missing thing!")
}
 
// On its own, this function isn’t super helpful.
throw()  // Error: Missing thing!
 
// By using the helper as a parameter’s default value,
// it only gets called when that parameter is missing.
const love = (thing = throw()) => `I love ${thing}!`
 
// Nothing changes in the regular case.
love("pizza")  // ⇒ "I love pizza!"
 
// The helper function throws an error if we don’t pass
// a value, effectively making the parameter required.
love()         // Error: Missing thing! ← better
Debug
none
Grid overlay