The spread operator allows functions, arrays, or variables to accept multiple arguments.
Using the Spread Syntax in function
function showSpread(one, two, three, four){ console.log(one); // w ww . j av a2s . c om console.log(two); console.log(three); console.log(four); } let myArray = [1,2,3,4]; showSpread(myArray[0], myArray[1], myArray[2], myArray[3]) //without using spread showSpread(...myArray); //using the spread syntax
Spread Operator to call Date constructor
let dayInfo = [1975, 7, 19]; let dateObj = new Date(...dayInfo); console.log(dateObj); //returns Tue Aug 19 1975 00:00:00 GMT-0400 (EDT)
Spread Operator in array literal
let numArray2 = [ 2, 3, 4, 5, 6, 7] let numArray = [1, ...numArray2, 8, 9, 10]; console.log(numArray); //returns 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 let part1 = [1,2,3]; let part2 = [4,5,6]; let part3 = [...part1, ...part2]; console.log(part3); //returns 1,2,3,4,5,6