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

Michael Hoffmann
Dec 26, 2022
| 1 min read
| 428 views
Michael Hoffmann
Dec 26, 2022
1 min read
| 428 views
Javascript

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:
1
const isRequired = () => {
2
throw new Error('Parameter is required!')
3
}
4
5
const foo = (bar = isRequired()) => {
6
console.log(bar)
7
}
8
9
foo() // throws the isRequired error
10
foo(undefined) // throws the isRequired error
11
foo(false) // logs "false"
12
foo(null) // logs "null"
13
foo('Test') // logs "true"
If you liked this tip, follow me on Twitter to get notified about new tips, blog posts, and more.
Show comments