Spread operator~ Basics ~

Spread operator

Back in the days when I started reading about the new features of JavaScript, I was the most excited about the spread operator. It allows us to expand iterable (or strings) in various places. Often I use this operator while constructing objects. For example:

const name = {
  firstName: "Krasimir",
  lastName: "Tsonev"
};

// Adding fields to an object
const profile = { age: 36, ...name };
console.log(profile); // age, first, last name

It works well also when we want to overwrite properties. Let's say that we want to update the age field of the profile above. We may do the following:

const updates = { age: 37 };
const updatedProfile = { ...profile, ...updates };
console.log(updatedProfile); // age=37

Another popular use case is when we want to pass multiple arguments to a function:

const values = [10, 33, 42, 2, 9];
console.log(Math.max(...values));
// instead of
console.log(Math.max(10, 33, 42, 2, 9));

Last but not least, the operator does a good job of clonning arrays. Not a deep clone but to avoid the mutation of the original object. Remember how we pass objects and arrays by reference (that's not entirely true) to functions. We may want to work with the array in such cases but avoid changing it. Look at the following example:

const values = [10, 33, 42, 2, 9];
function findBiggest(arr) {
  return arr.sort((a, b) => (a > b ? -1 : 1)).shift();
}
const biggest = findBiggest(values);
console.log(biggest), // 42
console.log(values); // [33, 10, 9, 2]

The findBiggest function sorts the array's items and returns the biggest one. The problem is that it's doing it with the shift method, which mutates the object. It leaves it with fewer items.

To solve this issue, we could use the spread operator.

const values = [10, 33, 42, 2, 9];
function findBiggest(arr) {
  return [...arr].sort((a, b) => (a > b ? -1 : 1)).shift();
}
const biggest = findBiggest(values);
console.log(biggest), // 42
console.log(values); // [10, 33, 42, 2, 9]