/
007.js
40 lines (30 loc) · 1.22 KB
/
007.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
Use the Rest Parameter with Function Parameters
Note:
ES6 introduces rest parameter for function parameters to help create more flexible functions.
We can create functions that take a variable number of arguments which are stored in an array that can be accessed later from inside the function.
function howMany(...args){
return 'You have passed ' + args.length + ' arguments.';
console.log(howMany(0, 1, 2));
console.log(howMany("string", null, [1, 2, 3], { })); // return You have passed 3 arguments. and You have passed 4 arguments.
}
The rest parameter eliminates the need to use the arguments object and allows us to use array methods on the array of parameters passed to the function howMany.
Instructions:
Modify the function sum using the rest parameter in such a way that the function sum is able to take any number of arguments and return their sum.
*/
// const sum = (x, y, z) => {
// const args = [x, y, z];
// let total = 0;
// for (let i = 0; i < args.length; i++) {
// total += args[i];
// }
// return total;
// }
const sum = (...args) => {
let total = 0;
for (let i = 0; i < args.length; i++) {
total += args[i];
}
return total;
}
console.log(sum(1,2,3,4));