JavaScript Spread Operator Refactor: Two Explanations Quiz
Refactor a manual `sum(nums[0], nums[1], nums[2])` call with the spread operator, two equivalent shapes (spread shortcut and the older `apply(null, nums)` form), plus companions on rest parameters and array-spread vs concat.
263 views
1
Refactor the snippet below so the call passes the array via the spread operator (...nums) instead of indexing each element manually.
Examples
Example 1:
Input:
const sum = (a, b, c) => a + b + c;
const nums = [4, 5, 6];
sum(nums[0], nums[1], nums[2]);
Output: 15
Explanation: spread expands the array into positional arguments at call time.const sum = (a, b, c) => a + b + c;
const nums = [4, 5, 6];
console.log(sum(nums[0], nums[1], nums[2]));
// rewrite the call site using the spread operatorGiven const sum = (a, b, c) => a + b + c; and const nums = [4, 5, 6];, write the pre-ES6 equivalent of calling sum with the array's elements spread into positional arguments, using Function.prototype.apply(null, nums). Explain why apply was the only option before the spread operator and why it is still occasionally useful.
Examples
Example 1:
Input:
const sum = (a, b, c) => a + b + c;
const nums = [4, 5, 6];
sum.apply(null, nums);
Output: 15
Explanation: apply's second argument is an array of positional args, achieving the same spread effect.const sum = (a, b, c) => a + b + c;
const nums = [4, 5, 6];
// rewrite the call using apply
console.log(/* fill me in */ 'placeholder');Define a sum function that accepts ANY number of arguments using rest parameters (...nums). The function should return the total of its inputs. Demonstrate it called with 3, 5, and 0 arguments.
Examples
Example 1:
Input: sum(1, 2, 3, 4, 5)
Output: 15
Explanation: rest collects all positional args into an array.Example 2:
Input: sum()
Output: 0
Explanation: empty rest array reduces to 0 with an initial value.const sum = (/* fill in with rest */) => {
// reduce over the rest array
};Show how to merge three arrays into one using the spread operator, and contrast with Array.prototype.concat. Which approach is shorter and when does each one shine?
Examples
Example 1:
Input:
const a = [1, 2], b = [3, 4], c = [5];
[...a, ...b, ...c]
Output: [1, 2, 3, 4, 5]
Explanation: spread expands each array in place.const a = [1, 2];
const b = [3, 4];
const c = [5];
// merge a, b, c into one array, two ways