Spread (three dots ...) operator in javascript


In this post, we're going to break down one of the most popular new features of the JavaScript language - the Spread operator (aka the three-dot operators ... ).

What does it do? 

The spread operator allows an expression to be expanded in places where multiple elements/variables/arguments are expected.
let’s look at a bunch of examples to better understand what in the heck the spread operator actually is.

Calling Functions without Apply

To this point we've called Function.prototype.apply, passing an array of arguments, to call a function with a given set of parameters held by an array:

function doSpread (x, y, z) { }
var args = [0, 1, 2];
// Call the function, passing args
doSpread.apply(null, args);

With the spread operator, we can avoid apply all together and simply call the function with the spread operator before the array:
The code is shorter, cleaner, and no need to use a useless null!

Spread Operators for Arrays

The core piece to know is the ... syntax. This is the spread operator, and it essentially takes either an array or an object and expands it into its set of items. This lets you do fancy things, so for example if you have the code:
const array = [1, 2];
const array2 = [...array, 3, 4];
The value of array2 will end up being [1, 2, 3, 4].

The spread operator lets you essentially drop an array in and get its values.
Coming back to our original code example, at the outer level what we have is
images = [...images.slice(0, index), {some stuff}, ...images.slice(index+1)]
What this is saying is: set the images array to be the old images array from 0 to index, followed by a new thing that we'll cover shortly, followed by the old images array from index+1 to the end.

In other words, we're going to replace the item at index.

Spread Operators for String to Array

Bonus example: Use the spread operator to simply convert a string to an array of characters
var str = "hello javascript";
var chars = [...str];
// ["h", "e", "l", "l", "o", " ", "j", "a", "v", "a", "s", "c", "r", "i", "p", "t"]

The spread operator walks through each character in the str string and assigns it to our new chars array.


Post a Comment

Post a Comment (0)