Javascript is required
Mokkapps LogoMichael Hoffmann

JavaScript Tip: Throw an Error if a Required Parameter Is Missing

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Dec 26, 2022
1 min read
|
20 views
Javascript
JavaScript Tip: Throw an Error if a Required Parameter Is Missing Image

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

We can use this approach to write a function that throws an error if a required parameter is missing:

index.js
const isRequired = () => {  throw new Error('Parameter is required!')}const foo = (bar = isRequired()) => {  console.log(bar)}foo() // throws the isRequired errorfoo(undefined) // throws the isRequired errorfoo(false) // logs "false"foo(null) // logs "null"foo('Test') // logs "true"

If you liked this tip, follow me on Twitter to get notified about new tips, blog posts, and more.