What are rest parameters and rest variables in JavaScript?

Rest Parameters allow you to gather an ordered list of arguments from a function call into a single variable. The variable can be an array, or an object, depending on how you declare it.

The syntax for using Rest Parameters is as follows:


params is an array of all the arguments you want to collect.

You can access the individual parameters in the params array by their position number. So, the first parameter would be params[0], the second would be params[1], and so on.

Rest Parameters are particularly useful when you don’t know in advance how many parameters a function will need. This can be the case when you’re calling a function from another function, or when you’re reading data from a file or socket.

Here’s an example of how you might use Rest Parameters:

function getMessage(message, user, date) {
	console.log(`${user} said: ${message} on ${date}`);
getMessage("Hello!", "Bob", "Today");

In this example, the getMessage function takes three parameters – message, user, and date. However, it’s possible to call the function with more or fewer parameters. When you call getMessage with fewer than three parameters, the extra parameters are set to undefined. When you call it with more than three parameters, the extra parameters are ignored.

Rest Parameters can also be used to create functions that accept an arbitrary number of arguments. Here’s an example:

function sum(...values) {
    var total = 0;
    values.forEach(function(value) {
    	total += value;
    return total;

sum(1, 2, 3);
sum(1, 2, 3, 4, 5);

In this example, the sum function takes any number of arguments. The values variable will be set to an array containing all the arguments that were passed to the function. The forEach function is then used to add each argument to the total variable.

You can also use the spread operator (…) to access the individual values in a Rest Parameters variable. Here’s an example:

function getUser(name, ...users) {
	console.log(`User ${name} is one of the following users:`);
    users.forEach(function(user) {

getUser("Alice", ["Bob", "Charlie"]);

In this example, the getUser function takes two parameters – name and users. The users variable is an array containing all the users that were passed to the function. The forEach function is then used to print out the name and value of each user.