This content originally appeared on Go Make Things and was authored by Go Make Things
Last week, I shared my preferred way to pass large set of arguments into a function using object destructuring and the Object.assign()
method.
function wizard (args) {
// Get the argument values
let {name, job, spell, isEvil} = Object.assign({
job: 'Wizard',
spell: null,
isEvil: false
}, args);
console.log(name, job, spell, isEvil);
}
A few astute readers wrote to me letting me know that you can achieve the same result by destructuring directly in the parameter assignment. You can even assign default parameter values.
function wizard ({name, job = 'Wizard', spell, isEvil = false} = {}) {
console.log(name, job, spell, isEvil);
}
With either approach, you then pass in your arguments like this.
// logs "Merlin", "Wizard", "Dancing teacups", false
wizard({
name: 'Merlin',
spell: 'Dancing teacups'
});
Personally, I find the use of Object.assign()
a bit easier to scan and read because each parameter is on its own line. The “shorthand” version feels too cluttered for my taste.
But they both do the same thing, so use whichever one you find easier to read and work with.
⏰🦉 Early Bird Sale! Today through Monday, get 30% off registration in the next session of the Vanilla JS Academy.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2021-11-30T15:30:00+00:00) Another way to destructure function arguments with vanilla JavaScript. Retrieved from https://www.scien.cx/2021/11/30/another-way-to-destructure-function-arguments-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.