DEV Community

Brandon Weaver
Brandon Weaver

Posted on

4 2

Spread Syntax

The spread operator is one feature of JavaScript which I often overlook. This week, I wanted to take a deeper look into spread syntax and write a short summary of the benefits.

First, and probably the most common use of the spread operator, shallow-cloning. Sure, we can get a shallow copy of an array from the slice method, but the spread syntax looks a little cleaner to me.

let arr1 = [1, 2, 3];

// slice
let arr2 = arr1.slice();

// spread
let arr3 = [ ...arr1 ];

// arr2 value: [1, 2, 3]
// arr3 value: [1, 2, 3]

We can also use the spread operator to get a shallow copy of an object.

let obj1 = { v1: 0, v2: 1 };

let obj2 = { ...obj1 };

// obj2 value: { v1: 0, v2: 1 }

Another great use of the spread operator, array concatenation.

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

// concat
let arr3 = arr1.concat(arr2);

// spread
let arr4 = [ ...arr1, ...arr2 ];

// arr3 value: [1, 2, 3, 4, 5, 6]
// arr4 value: [1, 2, 3, 4, 5, 6]

You're able to merge objects this way as well.

let obj1 = { v1: 0, v2: 1, v3: 2 };
let obj2 = { v2: 10, v3: 20 };

let obj3 = { ...obj1, ...obj2 };

// obj3 value: { v1: 0, v2: 10, v3: 20 }

It's also possible to pass multiple arguments to a function or method, using the spread operator.

const add = (a, b) => {
    return a + b;
}

let args = [10, 11];

let result = add( ...args );

// result value: 21

I do think that spread syntax can help to improve the cleanliness of our code. If you know of any other neat tricks or tips, please leave a comment below.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay