spread arguments javascript code example

Example 1: spread operator javascript

const parts = ['shoulders', 'knees']; 
const lyrics = ['head', ...parts, 'and', 'toes']; 
//  ["head", "shoulders", "knees", "and", "toes"]

Example 2: spread operator

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

Example 3: spread operator javascript

[a, b, ...objIteravel] = [1, 2, 3, 4, 5];

Example 4: 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