spread operator params javascript code example
Example 1: spread operator
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
// This will add each item in number arrray in sum method.
console.log(sum.apply(null, numbers));
// expected output: 6
Example 2: js spread parameters
// seperate each element of array using ...
let list = ['a','b','c'];
let copy = [...list, 'd', 'e']; // ['a', 'b', 'c', 'd', 'e']
//use for infinite parameters to a function
function toDoList(...todos) {
//todos is an array, so it has map function
document.write(
`<ul>${todos.map((todo) => `<li>${todo}</li>`).join("")}</ul>`
);
}
toDoList("wake up", "eat breakfast", ...list); //ul containing: wake up eat breakfast a b c