DEV Community

Cover image for THE JAVASCRIPT 'SPREAD' OPERATOR
Maame Afia Fordjour
Maame Afia Fordjour

Posted on

THE JAVASCRIPT 'SPREAD' OPERATOR

Introduction

An iterable, such as an array or string, can be expanded in locations where zero or more arguments (for function calls) or elements (for array literals) are anticipated by using the spread() syntax. The spread syntax lists an object's properties in an object literal and appends the key-value pairs to the object that is being produced.

Spread syntax has the same appearance as rest syntax. Spread syntax can be thought of as the antithesis of rest syntax. Whereas rest syntax gathers several elements and "condenses" them into a single element, spread syntax "expands" an array into its elements.

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// Expected output: 6

console.log(sum.apply(null, numbers));
// Expected output: 6

Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Syntax;

myFunction(a, ...iterableObj, b)
[1, ...iterableObj, '4', 'five', 6]
{ ...obj, key: 'value' }

Enter fullscreen mode Exit fullscreen mode

When a function call's arguments list has to be applied one element at a time or when every element from an object or array needs to be included in a new array or object, spread syntax might be used. The spread syntax is accepted in three different locations:

πŸ“Œ Object literals ({ ...obj, key: 'value' })

πŸ“Œ Array literals ([1, ...iterableObj, '4', 'five', 6])

πŸ“Œ Function arguments list (myFunction(a, ...iterableObj, b))

Array literals and argument lists can only include iterable values, such as String and Array. Many items, like all plain objects without a Symbol, are not iterable.iterator technique:

const obj = { key1: "value1" };
const array = [...obj]; // TypeError: obj is not iterable
Enter fullscreen mode Exit fullscreen mode

Conversely, spreading in object literals lists the value's own attributes. Arrays can be distributed across objects because all of an array's indices are enumerable own properties.

const array = [1, 2, 3];
const obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }
Enter fullscreen mode Exit fullscreen mode

Any primitive can be distributed between objects. Spreading anything else doesn't impart properties to the new object; only strings have enumerable own properties.

const obj = { ...true, ..."test", ...10 };
// { '0': 't', '1': 'e', '2': 's', '3': 't' }
Enter fullscreen mode Exit fullscreen mode

Replace apply()

Function.prototype.apply() is frequently used when you wish to pass an array's elements as parameters to a function.

function myFunction(x, y, z) {}
const args = [0, 1, 2];
myFunction.apply(null, args);
Enter fullscreen mode Exit fullscreen mode

Spread syntax allows the following to be written as:

function myFunction(x, y, z) {}
const args = [0, 1, 2];
myFunction(...args);
Enter fullscreen mode Exit fullscreen mode

Spread syntax can be applied to any argument in the argument list, and it can be applied more than once.

function myFunction(v, w, x, y, z) {}
const args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);
Enter fullscreen mode Exit fullscreen mode

Apply for new operator

It is not allowed to utilize an array and apply() directly when invoking a constructor with newbecause apply() calls the target function rather than building it, which results in a number of issues, including new.target being undefined. Nonetheless, spread syntax makes it simple to use an array with new:

const dateFields = [1970, 0, 1]; // 1 Jan 1970
const d = new Date(...dateFields);

Spread in array literals

The array literal syntax is no longer sufficient to build a new array utilizing an existing array as one of its parts without spread syntax. Rather, one must employ a variety of functions, such as push(), splice(), concat(), etc., when working with imperative code. This is far more concise with spread syntax:

const parts = ["shoulders", "knees"];
const lyrics = ["head", ...parts, "and", "toes"];
//  ["head", "shoulders", "knees", "and", "toes"]
Enter fullscreen mode Exit fullscreen mode

Just like spread for argument lists, ... can be used anywhere in the array literal, and may be used more than once.

Copying an array

Spread syntax can be used to create a shallow replica of an array. Every element in the array is unique and is not duplicated.

const arr = [1, 2, 3];
const arr2 = [...arr]; // like arr.slice()

arr2.push(4);
// arr2 becomes [1, 2, 3, 4]
// arr remains unaffected
Enter fullscreen mode Exit fullscreen mode

When copying an array, spread syntax efficiently travels one step deeper. For this reason, it might not be appropriate when copying multidimensional arrays. The same is true for Object.assign(); no JavaScript native action performs a deep clone. Values of specific supported kinds can be deeply copied using the web API method structuredClone().

Top comments (0)