This article has been imported from coding4.gaiama.org and is not necessarily up to date!
ES6 object destructuring mandatory parameters
Published:
Last updated:
Couple of days ago I came across this cool trick to validate required fields using ES6 default function parameters.
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

Can Rau
Doing web-development since around 2000, building my digital garden with a mix of back-to-the-roots-use-the-platform and modern edge-rendered-client-side-magic tech 📻🚀
Living and working in Cusco, Perú 🦙