Categories
Codes Javascript

7 Tricks of JavaScript Spread (…) Operator

“Any sufficiently advanced technology is indistinguishable from magic.”

― Arthur C. Clarke, Profiles of the Future: An Inquiry Into the Limits of the Possible

Introduction

JavaScript ES6 introduces the new spread operator (...) for easier and more beautiful code. Mozilla describes the spread operator as this:

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

The description is more complicated than the uses, trust me. This operator will change the way you code. So, without further ado, let’s start with the basics of using the spread operator.

Basics

The keyword is spread. So, it expands the elements of an object or an array. Here is an example for easier understanding:

const arr = ['a','b','c'];
console.log(arr); // ["a", "b", "c"]
console.log(...arr); // "a", "b", "c"
console.log("a","b","c"); // "a", "b", "c"

As you can see, the result of console.log(...arr); is the same with console.log("a","b","c");. The operator takes all the individual elements separately.

Now that you know what it does, let’s move to the first trick.

Properly Duplicate Array / Object

When we think of duplicating an object or array, we would do something like this:

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

//------------------------------------------

const obj = { a:'A', b:'B', c:'C' };
const objCopy = obj;
console.log(obj); // { a:'A', b:'B', c:'C' }
console.log(objCopy); // { a:'A', b:'B', c:'C' }

Does it copy the array or object? Well, sort of. As long as the data does not change. When you change the data from the copied array or object, the original one will also change. See the example below:

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

arrCopy.push(6);
console.log(arr); // [1,2,3,4,5,6]
console.log(arrCopy); // [1,2,3,4,5,6]

// ----------------------

const obj = { a:'A', b:'B', c:'C' };
const objCopy = obj;
console.log(obj); // { a:'A', b:'B', c:'C' }
console.log(objCopy); // { a:'A', b:'B', c:'C' }

objCopy.c = 'X';
console.log(obj); // { a:'A', b:'B', c:'X' }
console.log(objCopy); // { a:'A', b:'B', c:'X' }

Why do this happen? Because JavaScript assigns the copy to refer to the original. They both point to the same memory: arr with arrCopy, and obj with objCopy.

So, how do we create a copy from the original, but when we change the value of the copy, the original does not change?

What we will do is by changing the initialization:
const arrCopy = arr; to const arrCopy = [ …arr ];
const objCopy = obj; to const objCopy = { …obj };

See this example below:

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

arrCopy.push(6);
console.log(arr); // [1,2,3,4,5]
console.log(arrCopy); // [1,2,3,4,5,6]

// ----------------------

const obj = { a:'A', b:'B', c:'C' };
const objCopy = { ...obj };
console.log(obj); // { a:'A', b:'B', c:'C' }
console.log(objCopy); // { a:'A', b:'B', c:'C' }

objCopy.c = 'X';
console.log(obj); // { a:'A', b:'B', c:'C' }
console.log(objCopy); // { a:'A', b:'B', c:'X' }

Merge Array / Object

Merging an array or object with spread operator is very simple. You just have to create an empty array or object, with variables that are expanded with the spread operator. Here is an example:

const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [7,8,9];
const mergedArr = [...arr1, ...arr2, ...arr3];
console.log(mergedArr);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

const objA = { a:'A', b:'B' };
const objB = { c:'C', d:'D' };
const mergedObj = { ...objA, ...objB };
console.log(mergedObj);
// { a: "A", b: 'B', c: "C", d: "D" }

So, there won’t be any need to expand the elements one by one and put them to the new merged array or object. Pretty cool, huh?

Math.min and Math.max

In JavaScript, to get the minimum number from every parameter, use Math.min(). And to get the maximum number, use Math.max(). Look at the example below:

const min = Math.min(1,0,4,2,-1,-3);
console.log(min); // -3

const max = Math.max(1,0,4,2,-1,-3);
console.log(max); // 4

The problem is, both Math.min() and Math.max() cannot accept an Array parameter. Both functions will return NaN. So, we use the spread operator to solve the problem, shown as this example:

const list = [1,0,4,2,-1,-3];

console.log(Math.min(list)); // NaN
console.log(Math.max(list)); // NaN
console.log(Math.min(...list)); // -3
console.log(Math.max(...list)); // 4

Passing Arguments

You just read the Math.min() and Math.max() functions used with spread operators. Did you wonder on how to create a function which can accept multiple arguments?

It’s quite simple: Put the spread operator in front of a variable used as the parameters when declaring a function. And then, you can put as many arguments as you want to when calling that function (But make sure you already handled it). See this snippet below as an example:

const dynamicFunc = (arg1, ...args) => {
   console.log("arg1: " + arg1); 
   console.log("args: " + args);
};

dynamicFunc(1,2,3,4,5); 
// arg1: 1 
// args: [2,3,4,5]

args will be parsed as an array of arguments. And it can support quite many.

Convert String To List of Characters

You can convert a string to a list of characters very easily with the spread operator. This can be done because a string is also an iterable. See the example below:

const word = "Coding";
const arrOfChar = [...word];
console.log(arrOfChar); // ["C", "o", "d", "i", "n", "g"]

Remove Duplicates

Combined with the Set native object, the spread operator can be used to remove any duplicates that exist in an array. Just create a new array containing a spread operator of a new Set from an array that has duplicates. Or, see the example below for more clarity:

const arr = [1,2,3,3,5,8,8,true,true,"books","books","books",null,2];

const unique = [...new Set(arr)];

console.log(unique);
// [1, 2, 3, 5, 8, true, "books", null]

Put ...new Set(arr) on initializing a new array, that new array will have unique values.

Rest Operator

The last trick of the ... operator is the usage of rest operator. As expected from its name, it enables you to get the remainder (the rest) of values in a deconstructed array, as a smaller array. See the example below:

const [ first, ...rest ] = ['a','b','c'];
console.log(first, rest);
// 'a' [ 'b', 'c' ]

So, after defining first to be 'a', the existence of the ... operator preceding rest makes sure that the rest of values will belong to an array. Should rest has no ... operator, it will have 'b' as a value.

Conclusion

The spread operator is a very useful feature for you to work with, mostly with arrays and objects. Because, this operator make some cases such as merging very simple. In the end, we can save time on coding merging functions just by using the spread operator.

I hope you learnt something new here! Do you have any other tricks to use using spread operator? Let me know in the comments!

Live your code and code your life!

“It’s still magic even if you know how it’s done.”

― Terry Pratchett, A Hat Full of Sky

By Ericko Yap

Just a guy who is obsessed to improve himself. Working as a programmer in a digital banking company. Currently programming himself in calisthenics, reading books, and maintaining a blog.

Leave a Reply

Your email address will not be published. Required fields are marked *