DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Micheal Adisa
Micheal Adisa

Posted on • Updated on

SPREAD IN JAVASCRIPT

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]
Enter fullscreen mode Exit fullscreen mode
newArray = [...array1, ...array2]
console.log(newArray) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode
const newNums = [...nums1, ...nums2]
console.log(Math.max(...newNums));    // 9
console.log(Math.min(...newNums));    //  1
Enter fullscreen mode Exit fullscreen mode

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)

An Animated Guide to Node.js Event Lop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.