Oh i just finished washing my clothes i need them to be side by side on a line, i’ll spread them right? This sounds quite abstract, let’s see how this relates to javascript.
The javascript spread function is denoted by three dots ‘...’ (PS: Ignore the quotes). It was added to JavaScript in ES6 (ES2015) and is useful for adding items to an array, combining array and objects into a place and spreading an array out into a function’s arguments.
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 NaN. Try this; console.log(Math.min(newNums)); // NaN I’m sure you’re asking why this happened right?. Well, Math.max or Math.min and any other Math operator expects a list of numeric arguments, not a single array.
This actually gives us a javascript superpower, love to see it! 😀.