This content originally appeared on Go Make Things and was authored by Go Make Things
Today, I want to talk about a way to handle passing arguments into functions when there’s more than two or three of them that I think results in a better experience for everyone.
Let’s dig in!
An object of arguments
If I have just two or three parameters, I’ll accept them as individual arguments just like you would expect.
function wizard (name, job) {
// ...
}
But once I have more arguments than that, remembering the order of the accepted parameters becomes difficult.
I’ve found that it’s easier at that point to accept an object of options. Inside the function, you can use object destructuring to get individual parameter values from it.
function wizard (args) {
// Get the argument values
let {name, job, spell, isEvil} = args;
}
Default parameters
I like to pair this approach with the Object.assign()
method to merge the provided arguments into some smart defaults.
function wizard (args) {
// Get the argument values
let {name, job, spell, isEvil} = Object.assign({
job: 'Wizard',
spell: null,
isEvil: false
}, args);
}
This allows users to pass in just the required arguments, and fallback on defaults if desired.
wizard({
name: 'Merlin',
spell: 'Dancing teacups'
});
🔥 Black Friday Sale! Today through Monday, save 50% on every pocket guide, video course, and enrollment in the Vanilla JS Academy. If you buy a pocket guide bundle or join Academy, you'll also get $436 in free bonus gifts. This sale ends Monday, so don't wait!
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2021-11-24T15:30:00+00:00) My preferred way to pass arguments into a function with vanilla JavaScript. Retrieved from https://www.scien.cx/2021/11/24/my-preferred-way-to-pass-arguments-into-a-function-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.