Rest Parameter and Spread Operator
Rest Parameter…
It is denoted by 3 dots(…). The dots(…) means gather the remaining parameters into an array. Below shows the code of rest operator.
function add(...args){
args.map(i=>console.log(i))
}
add(1,2) //1, 2
Spread Operator
It looks similar to rest operator with 3 dots …, but does quite the opposite.
When ...arr
is used in the function call, it “expands” an iterable object arr
into the list of arguments.
- For
Math.max
:
const array =[1, 2, 3, 4]
alert( Math.max(...arr) ); // 5 (spread turns array into a list of arguments)
2. We can combine spread operator for adding in array values.
const v1 = [1,2,3];
const v2 = [4,5,6];
const v3 = [...v1,0,...v2];
console.log(v3) // [1,2,3,0,4,5,6]
3. String into array of characters
const str = 'Hello'
console.log([...str]) // ["h", "e", "l", "l", "o"]
const str1 = 'Hello baby'
console.log([...str1]) //["h", "e", "l", "l", "o", " ", "b", "a", "b", "y"]
4. Copy array/object
const value1 = [1,2,3]
const value2 = [...value1] // spread the array into a list of parameters then put the result into a new array
console.log(value2) // [1,2,3]
// are the arrays equal?
alert(value1 === value2); // false (not same reference
// modifying our initial array does not modify the copy:
value2.push(4);
alert(value2); // 1, 2, 3, 4
alert(value1); // 1, 2, 3
Summary
When we see "..."
in the code, it is either rest parameters or the spread syntax. The spread operator allows us to spread the value of an array (or any iterable) across zero or more arguments in a function or elements in an array (or any iterable). The rest parameter allows us to pass an indefinite number of parameters to a function and access them in an array.