Language: EN

javascript-operador-spread

Spread Operator in JavaScript

The spread operator (...) allows you to expand elements of arrays and objects to obtain their individual elements.

Introduced in ECMAScript6 (2015), the spread operator is extremely useful for working with arrays, objects, and functions, simplifying many common tasks.

Instead of using more complicated techniques to manipulate data, the spread operator provides a more direct and readable syntax (this improves code readability, which is always a plus 😉).

The spread operator is very very powerful. You should get used to it and enjoy its benefits.

Syntax of the spread operator

The basic syntax of the spread operator is as follows:

const array = [1, 2, 3];
const newArray = [...array, 4, 5];
console.log(newArray); // [1, 2, 3, 4, 5]

In this example,

  • We created an array
  • The spread operator ...array is used to “explode” the original array
  • We add 4 and 5 to its elements
  • We use this to generate a newArray with the elements of the original array, adding new elements at the end.

Using the spread operator with Arrays

Expanding an Array

One of the most common uses of the spread operator is to create new arrays from existing arrays. This is useful for copying arrays or combining several arrays into one:

const array1 = [1, 2, 3];
const array2 = [...array1, 4, 5, 6];

console.log(array2); // Result: [1, 2, 3, 4, 5, 6]

In this example,

  • The spread operator ...array1 expands the elements of array1 into array2, creating a new array by combining both.

Copying Arrays

The spread operator also allows you to create shallow copies of arrays, which is useful to avoid side effects in data manipulation operations:

const original = [1, 2, 3];
const copy = [...original];

console.log(copy); // [1, 2, 3]

This approach is cleaner and more expressive than using traditional methods like slice() to copy arrays.

Adding Elements to Arrays

You can use the spread operator to add elements to an existing array without mutating (without modifying) the original array:

const numbers = [1, 2, 3];
const newNumber = 4;
const updated = [...numbers, newNumber];
console.log(updated); // [1, 2, 3, 4]

Concatenating Arrays

Similarly, we can easily concatenate two arrays.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const concatenatedArray = [...array1, ...array2];

console.log(concatenatedArray); // Result: [1, 2, 3, 4, 5, 6]

Manipulating Nested Arrays

The spread operator can also be useful for working with nested arrays:

const matrices = [[1, 2], [3, 4]];
const combined = [].concat(...matrices);
console.log(combined); // [1, 2, 3, 4]

Using the spread operator with Objects

Creating New Objects

The spread operator can expand properties from one object into another object, allowing the creation of new objects based on existing ones:

const person = { name: 'Juan', age: 30 };
const address = { street: 'Fake Street', city: 'Springfield' };

const completePerson = { ...person, ...address };

console.log(completePerson); // { name: 'Juan', age: 30, street: 'Fake Street', city: 'Springfield' }

In this example, completePerson combines the properties of person and address.

Copying Objects

Just like with arrays, the spread operator allows you to make shallow copies of objects:

const original = { a: 1, b: 2 };

const copy = { ...original };

console.log(copy); // { a: 1, b: 2 }

This approach is useful for creating modified versions of objects without altering the original.

Updating Object Properties

You can use the spread operator to update properties of an object without mutating the original object:

const user = { name: 'Ana', age: 25 };

const updated = { ...user, age: 26 };

console.log(updated); // { name: 'Ana', age: 26 }

Here, the spread operator is used to create a new object with an updated property.

Passing Arguments to a Function

function sum(a, b, c) {
  return a + b + c;
}

const numbers = [1, 2, 3];

const result = sum(...numbers);

console.log(result); // Result: 6

Here, the spread operator is used to pass the elements of the numbers array as individual arguments to the sum function.

It is important not to confuse the spread operator with the rest operator (...). Although they use a similar syntax, they are employed in different contexts.

Destructuring and Spread

In combination with destructuring, the spread operator allows you to extract part of an object and combine it with other values:

const person = { name: 'Luis', age: 28, profession: 'Engineer' };

const { name, ...rest } = person;

console.log(name); // 'Luis'
console.log(rest); // { age: 28, profession: 'Engineer' }

Here, rest contains all the properties of person except name.

The spread operator can have performance implications in operations with large amounts of data, as it creates shallow copies of arrays and objects.

It is advisable to use it carefully in situations where performance is a critical concern.

(But don’t obsess over it either.)