Spread operator in JavaScript

I loved the new spread operator of javascript that came with ES6. Basically, it has three dots. You might be familiar with the varagrs in Java. However, it’s more than varargs. Let me give you some examples-

Let’s say you have a variable-

var a= [1,2,3,4];
var b = [5,7];

and you wanna concatenate a and b . There is a function to do that –

var d = a.concat(b) ;
console.log(d);

Output: [1, 2, 3, 4, 5, 7]

but certainly, you can’t do the following-

var e = [a, b];
console.log(e);

because it will end up an array of arrays. The output of it would be –

[[1, 2, 3, 4], [5, 7]]

However, we can use spread operator (…) to concatenate two arrays.

var f = [...a, ...b];
console.log(f);

output: [1, 2, 3, 4, 5, 7]

The three dots are used as a spread operator. It can be used as a destructuring assignment .

For example –

var foo = ["one", "two", "three"];
var [one, two, three] = foo;

console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s