DEV Community

Micheal Adisa
Micheal Adisa

Posted on • Edited on

1

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! 😀.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

Retry later