1function sum(...numbers) {
2 return numbers.reduce((accumulator, current) => {
3 return accumulator += current;
4 });
5};
6
7sum(1,2) // 3
8sum(1,2,3,4,5) // 15
1function sum(x, y, z) {
2 return x + y + z;
3}
4
5const numbers = [1, 2, 3];
6
7console.log(sum(...numbers));
8// expected output: 6
9
10console.log(sum.apply(null, numbers));
11// expected output: 6
12
13/* Spread syntax (...) allows an iterable such as an array expression or string
14to be expanded in places where zero or more arguments (for function calls)
15or elements (for array literals) are expected, or an object expression to be
16expanded in places where zero or more key-value pairs (for object literals)
17are expected. */
18
19// ... can also be used in place of `arguments`
20// For example, this function will add up all the arguments you give to it
21function sum(...numbers) {
22 let sum = 0;
23 for (const number of numbers)
24 sum += number;
25 return sum;
26}
27
28console.log(sum(1, 2, 3, 4, 5));
29// Expected output: 15
30
31// They can also be used together, but the ... must be at the end
32console.log(sum(4, 5, ...numbers));
33// Expected output: 15
34