const array1 = [ 1, 2, 3, 4 , 5] const array2 = [ 6, 7, 8, 9, 10]
newArray = [...array1, ...array2] console.log(newArray) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Just like that! Our spread function works well as expected. You can go on and on to combine lots of array together into one (side by side 😀)
Interesting stuff, it can also be used in Math functions.
const nums1 = [2, 7, 8, 5] const nums2 = [4, 1, 9, 3]
const newNums = [...nums1, ...nums2] console.log(Math.max(...newNums)); // 9 console.log(Math.min(...newNums)); // 1
If you tried to log
newNums max number or minimum number without the spread syntax, you’ll get
Try this; c
onsole.log(Math.min(newNums)); // NaN
I’m sure you’re asking why this happened right?. Well,
Math.min and any other Math operator expects a list of numeric arguments, not a single array.