JavaScript ES6 Spread Operator

This is in response to a FreeCodeCamp curriculum session which teaches spread operators.

I found FCC’s explanation of spread operators (click here) to be a very complex description of a simple concept.

Thank you to Brandon Morrelli’s article which provided a clear description of how spread operators can be used to make it easy to work with arrays.

How the Spread Operator Works

Here is the simple way of understanding how a spread operator works:

var arr1 = ['three', 'four'];

var arr2 = ['one', 'two', ...arr1, 'five', 'six'];

console.log(arr2);
// logs [ 'one', 'two', 'three', 'four', 'five', 'six' ]

Essentially the spread operator allows us to inject arrays into spots where we want only the elements, not the array container.

Here is an example of what happens when we don’t have a spread operator:

var arr1 = ['three', 'four'];

var arr2 = ['one', 'two', arr1, 'five', 'six'];

console.log(arr2);
// logs [ 'one', 'two', [ 'three', 'four' ], 'five', 'six' ]

In the example above, we have a nested array which could be problematic depending on the architecture of your application.

Essentially, this makes it so we can evaluate arrays in place.

ES6: Use the Spread Operator to Evaluate Arrays In-Place

This is the answer that passes the tests in the current version of Free Code Camp:

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
(function() {
  "use strict";
  arr2 = [...arr1];
})();
console.log(arr2);

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.