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 ...
. 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! π.
Top comments (0)