Spread Operator in Javascript

Math.max(1,2,3) // 3Math.max([1,2,3]) // NaN
Math.max(…[1,2,3]) // 3
  • Copying an array
const nums = [1,2,3,4,5]const moreNums = [...nums]console.log(moreNums) //[1,2,3,4,5]
  • Concatenating or combining arrays
const firstArr = [1,2,3]const secondArr = [4,5,6]const addBothArr = [...firstArr,...secondArr]console.log(...addBothArr) //[1,2,3,4,5,6]
  • Using an array as arguments
const nums = [1, 2, 3];const showNums = (f1, f2, f3) => { console.log(`show numbers: ${f1}, ${f2}, ${f3}`) };showNums(...nums); //show numbers: 1, 2, 3nums.pop();nums.pop();nums.push(4);nums.push(5);showNums(...nums); //show numbers: 1, 4, 5nums.pop();nums.pop();showNums(...nums, 6); //show numbers: 1, 6, undefined
  • Adding an item to a list
const nums= [1,2,3]const addMoreNums = [4,5,6,...nums]console.log(addMoreNums) // [1,2,3,4,5,6]
  • Combining objects
const objectOne = {firstName: "John"}const objectTwo = {lastName: "Smith"}const objectThree = {...objectOne, ...objectTwo, birthday: "01011990"}console.log(objectThree) // {firstName: "John", lastName: "Smith", birthday: "01011990"}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store