DEV Community

Tyn
Tyn

Posted on

JavaScript Spread Operator

JavaScript Spread Operator (…)

  • The Spread Operator in JavaScript expands (unpacks) an array into its individual elements.

*It’s used with both arrays and objects, in arrays it’s used when:

1. Building an Array
2. passing arguments into a function

1- Building an Array:

  • in here we can use it to expand an array element and use it in another (array for example).

const arr = [5, 6, 7];

// without the spread operator 😐

const badArr = [1, 2, 3, 4, arr[0], arr[1], arr[2]];
console.log(badArr); // [1, 2, 3, 4, 5, 6, 7]

// with the spread operator 😃

const goodArr = [1, 2, 3, 4, ...arr];
console.log(goodArr); // [1, 2, 3, 4, 5, 6, 7]

Enter fullscreen mode Exit fullscreen mode
  • as you can see, the spread operator makes things much easier.

  • if you again wanted the individual elements of the expanded array, use the spread operator:

console.log(...goodArr); // 1 2 3 4 5 6 7

//the line above is just like writing this code:

console.log(1, 2, 3, 4, 5, 6, 7); // 1 2 3 4 5 6 7
Enter fullscreen mode Exit fullscreen mode
  • another example to understand more:
const foods = ['chicken', 'meat', 'rice'];

const Newfoods = [...foods, 'pizza '];
console.log(Newfoods); // ['chicken', 'meat', 'rice', 'pizza ']
Enter fullscreen mode Exit fullscreen mode
  • keep in mind that here we are creating a completely new array, we are not changing (mutating) the foods array, look:
console.log(foods); // ['chicken', 'meat', 'rice']
Enter fullscreen mode Exit fullscreen mode
  • Spread Operator is similar to Destructuring, but the difference is that the spread operator doesn’t create new variables, so we can use it only in places where we write values separated by commas.

Two useful use cases of the spread operator with arrays:

1.creating a copy of an array:

const arrOriginal = [1, 2, 3, 4, 5];

const arrCopy = [...arrOriginal];
console.log(arrCopy); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

2.merging two or more arrays:

const arr1 = ['A', 'B', 'C'];
const arr2 = ['D', 'E', 'F'];

const mergedArr = [...arr1, ...arr2];
console.log(mergedArr); // ['A', 'B', 'C', 'D', 'E', 'F']
Enter fullscreen mode Exit fullscreen mode
  • The spread Operator does not only work on arrays, it also works on all iterables, which are things like: arrays, strings, maps and sets (most of the built-in data structures), but NOT (objects).
  • on strings: each letter on the original string = an individual element, example:
const str = 'spongeBob';

const letters = [...str, 'squarePants'];
console.log(letters); // ['s', 'p', 'o', 'n', 'g', 'e', 'B', 'o', 'b', 'squarePants']
Enter fullscreen mode Exit fullscreen mode
  • but remember, we still don’t want to use the spread operator other than in the two situations we specified at the top, which where “building an array” & “passing arguments”, because for example, if we wanted to use some values separated by commas to create a string by template literals, it won’t work and will give us an error, because it is not a place that expects multiple values separated by a comma:
console.log(`spelling sponge bob's name: ${...str}`);  // Expression expected

Enter fullscreen mode Exit fullscreen mode

2- passing arguments into a function

function orderDrink(drink1, drink2) {
  console.log(`Your Ordered drinks are ${drink1} and ${drink2}`);
}


const drinks = ['water', 'juice'];

orderDrink(...drinks);


// if you did it without the Spread Operator, it would be like this
orderDrink(drinks[0], drinks[1]); 
Enter fullscreen mode Exit fullscreen mode
  • Using Spread Operator:
  • Starting with ES2018, The Spread Operator actually also works for objects, even though objects are not iterables, example:
const restaurant = {
  name: 'spongeBob restaurant',
  location: 'Bikini bottom',
  chef: 'spongeBob',
};

// adding new properties

const restaurantNew = { ...restaurant, netWorth: 'billions' };

// making a copy

const restaurantCopy = { ...restaurant };
Enter fullscreen mode Exit fullscreen mode
  • in the first one we created a new object with the same properties as the restaurant object, but we added another property which is the netWorth property.
  • in the second one, we made a copy of the restaurant object, note that Changes to the copied object do not affect the original object, and vice versa.

Hope you understood everything here, if you have any questions feel free to ask in the comments section, THANKS for reading 🙂

Top comments (0)