Thursday, 5 December 2024

Rest Parameters in JavaScript to accept an indefinite number of arguments

Rest parameters in JavaScript allow a function to accept an indefinite number of arguments as an array. This is useful when you want to create functions that can handle more arguments than you originally defined.

How Rest Parameters Work?

Rest parameters are indicated by three dots (...) followed by the name of the array that will hold the arguments. This syntax tells JavaScript to gather all remaining arguments into a single array.

 

Syntax

function functionName(...restParameter) {
  // function body
}

Example 1: Same Sum function can take 1 or many arguments and return sum of all the arguments passed.

 

sum.js

function sumAll(...numbers) {
  let sum = 0;
  for (let number of numbers) {
    sum += number;
  }
  return sum;
}

console.log(`sumAll(1) : ${sumAll(1)}`); 
console.log(`sumAll(1, 2) : ${sumAll(1, 2)}`); 
console.log(`sumAll(1, 2, 3) : ${sumAll(1, 2, 3)}`);

Output

sumAll(1) : 1
sumAll(1, 2) : 3
sumAll(1, 2, 3) : 6

In this example, the sumAll function takes a rest parameter numbers. All arguments passed to the function are collected into the numbers array. The function then iterates over this array and sums the values.

 

Example 2: Combining Rest Parameters with Other Parameters

You can also use rest parameters alongside regular parameters, but the rest parameter must be the last in the function definition.

 

mixedWithOtherParams.js

function introduce(greeting, ...names) {
  return `${greeting}, ${names.join(' and ')}!`;
}

// Output: Hello, Alice and Bob!
console.log(introduce('Hello', 'Hari', 'Ram')); 

// Output: Hi, John and Jane and Doe!
console.log(introduce('Hi', 'Hari', 'Ram', 'Krishna')); 

Output

Hello, Hari and Ram!
Hi, Hari and Ram and Krishna!

The introduce function takes a greeting and a rest parameter names. The greeting is a regular parameter, while names gathers the remaining arguments. The rest parameters are joined together with the word "and" to create a friendly greeting.

 

Rest Parameters vs arguments Object

Before rest parameters were introduced, the arguments object was used to handle multiple function arguments. However, rest parameters are preferred because:

 

1.   The arguments object is not a real array, so you have to convert it to an array if you want to use array methods.

2.   Rest parameters provide more clarity and flexibility, as they only capture the remaining arguments, not all arguments.

 

restParameterVsRegularParameter.js

function oldWay() {
  console.log(arguments);
}

function newWay(...args) {
  console.log(args); 
}

oldWay(1, 2, 3);
newWay(1, 2, 3);

Output

[Arguments] { '0': 1, '1': 2, '2': 3 }
[ 1, 2, 3 ]


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment