Skip to content
Coding4GaiAmaOpen Source straight from the jungle

#ES6 object destructuring mandatory parameters

Couple of days ago I came across this cool trick to validate required fields using ES6 default function parameters.

JavaScript
function throwRequired(name) {
throw new Error(`'${name}' is required`)
}
function name({
id = null,
name = 'user',
password = throwRequired('password'),
}) {
console.log('All is good, password is: ' + password)
}

I haven’t actually used it so far, just tested in Chrome DevTools.

Check out the StackOverflow question all this originates from.

Great article about this by Kent C. Dodds JavaScript default parameters

Discuss on Twitter
Share

Can Rau

Open Source & Rainforest Maintainer at GaiAma.org 🌴