LEARNING: The ES6 Spread Operator (...)
Today I'll be diving into the Javascript Spread Operator (...
), and its various use-cases.
The spread operator was released as part of ES6 (which was a major Javascript release a couple years back that introduced some awesome new JS syntax, functions, etc.). I recently came across it in a tutorial I was working through and didn't know what it was... you can learn along with me.
As mentioned in the post title, the spread operator is written as three periods: ...
It can be used, as the name suggests, to "spread" or expand the contents of an array or other iterable object into individual arguments. I had no idea what that really meant / how to apply it until I went through some examples, so here goes.
EX. 1: Combining Arrays
Let's start out with a simple example. We begin with an initial array:
let array1 = [1, 2, 3];
Now let's try to insert array1 into array2, below, and print the result. Note here we are NOT using the spread operator.
let array2 = [array1, 4, 5, 6];
console.log(array2);
// [[1, 2, 3], 4, 5, 6]
As you can see above, array1
is inserted into array2
as an array within an array. But what if we want to extract the values from array1
as individual arguments, so that we return one single array of individual values. We can use the spread operator to achieve this:
let array1 = [1, 2, 3];
let array2 = [...array1, 4, 5, 6];
console.log(array2);
// [1, 2, 3, 4, 5, 6]
EX. 2: Copying Arrays
Here's a similar example, that I think is slightly more confusing/nuanced. Take an initial array:
let array1 = ["a", "b", "c"];
What if we want to copy the contents of that array into a NEW array? Common sense might tell you that this is a fine solution:
let array2 = array1;
Even after we print it out, it looks kosher:
console.log(array2);
// ["a", "b", "c"]
But hold up, what happens when we try to manipulate our new array, array2
? I'll paste previous code below to illustrate this clearly:
let array1 = ["a", "b", "c"];
let array2 = array1;
array2.push("d") // we push a new value into array2
console.log(array2);
// ["a", "b", "c", "d"]
console.log(array1);
// ["a", "b", "c", "d"]
As you can see above, when we tried to manipulate array2
, array1
was also changed. We can use the spread operator to copy the contents of one array into another, and then manipulate the new array without affecting the original array. Like so:
let array1 = ["a", "b", "c"];
let array2 = [...array1]; // we use the spread operator to copy the array
array2.push("d") // we push a new value into array2
console.log(array2);
// ["a", "b", "c", "d"]
console.log(array1);
// ["a", "b", "c"]
EX. 3: Concatenating Arrays
Another similar use-case, we can use the spread operator to concatenate arrays:
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
// using the JS concat function:
let array3 = array1.concat(array2);
console.log(array3);
// [1, 2, 3, 4, 5, 6]
// using the spread operator:
let array3 = [...array1, ...array2];
console.log(array3);
// [1, 2, 3, 4, 5, 6]
EX. 4: Printing Array Contents Simple but powerful use case here -- Let's print the contents of an array using the spread operator.
array = ["cat", "dog", "fish"];
console.log(array); // without spread operator
// ["cat", "dog", "fish"]
console.log(...array); // WITH spread operator
// cat dog fish
You can see that using the spread operator prints/returns the three array components separately, as opposed to printing the array itself.
EX. 5: Convert Individual Nodes / Arguments Into an Array
Slightly different use case here... let's write a function that takes an arbitrary number of values as arguments, and creates an array out of them:
function argsToArray(...args) {
console.log(args);
};
argsToArray("left", "right", "up", "down"); // takes four individual strings as args
// ["left", "right", "up", "down"]
Or even more fun, we can use the same kind of spread operator logic + some DOM querying to create an array of DOM elements
[...document.querySelectorAll('p')]; // returns an array of all <p> elements on a page
EX. 6: Map Array Contents to Individual Function Args Sort of the exact opposite of the previous example, here we'll use the spread operator to "spread" the contents of an existing array to individual input args in a function:
// define an array of numbers
numsArray = [1, 2, 3, 4];
// define a function that takes four separate arguments and prints their sum
function addNums(a, b, c, d) {
console.log(a + b + c + d);
};
addNums(numsArray); // first we try to simply give the pre-defined number array as an argument
// some undefined nonsense
addNums(numsArray[0], numsArray[1], numsArray[2], numsArray[3]]; // we could separate the values manually, but this sucks
// 10
addNums(...numsArray); // or, we could just use the spread operator. Success!
// 10
Those are just few applications to get the juices flowin'. There are plenty more, which I'll hopefully explore in different contexts in future posts.
--
Thx for reading, love you guys,
noah
Comments
Post a Comment