JS Coding Questions Logo
JS Coding Questions
#186💼 Interview💻 Code

What is a rest parameter

Advertisement

728x90

Rest parameter is an improved way to handle function parameters which allows us to represent an indefinite number of arguments as an array. The syntax would be as below,

javascript
1function f(a, b, ...theArgs) {
2  // ...
3  }

For example, let's take a sum example to calculate on dynamic number of parameters,

javascript
1function sum(...args) {
2  let total = 0;
3  for (const i of args) {
4  total += i;
5  }
6  return total;
7  }
8
9console.log(sum(1, 2)); //3
10
11console.log(sum(1, 2, 3)); //6
12
13console.log(sum(1, 2, 3, 4)); //10
14
15console.log(sum(1, 2, 3, 4, 5)); //15

Note: Rest parameter is added in ES2015 or ES6

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 15

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
186of476