LennyShort.com

The JavaScript Rest Parameter

The "rest" parameter in JavaScript can be used to pass in an unknown number of arguments to a function. Say we have a function that sets permission levels for users, but we don't know how many users there are. We can use the "rest" parameter to pass in all of the users and have them handled properly:

function setPermissionLevel(permissionLevel, ...names) {
    names.forEach((name) => 
        console.log(`${name} now has ${permissionLevel} level access.`))

Now we can call the function and pass in an arbitrary number of user names to set:

setPermissionLevel('admin', 'Dave', 'Sally', 'Mike', 'Tom')

Here's the console output:

Console
›Dave now has admin level access.
›Sally now has admin level access.
›Mike now has admin level access.
›Tom now has admin level access.

Note that the "rest" parameter must be the last parameter that is passed into the function.

What I'm reading:

What I've read recently:

What's on my reading list: