Three dots in JavaScript : Spread & Rest Operators
function myFunction(x, y, ...data) { //REST OPERATOR
console.log(x); // "a"
console.log(y); // "b"
console.log(data); // ["c","d"]
console.log(...data); // "c" "d"
}var arr = ['a','b','c','d'];
myFunction(... arr); //SPREAD OPERATOR
Now let us try and understand what just happened here! Starting with the formal definition for Rest Parameters & Spread Operators.
Rest Parameters
It allows us to pass any number of arguments as an array. It is pretty helpful to write clean and non-repetitive code.
As in above example, prefixing ...
on data
allowed us to pass extraneous variables ( c & d ) to pass an arguments. Obviously only the ‘last’ parameter can be a ‘rest parameter’. If you try otherwise in console,
function myFunction(x, ...y, data) {
console.log(x);
}
var arr = ['a','b','c','d'];
myFunction(... arr);
Above would throw the ERROR as
Uncaught SyntaxError: Rest parameter must be last formal parameter
Spread Operators
According to MDN:
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
Simply put, Spread syntax is super useful to expand elements of an array expression or a string. It also makes joining of arrays neat. Let us take an example.
const a = ['Hi'];
const b = ['How', 'are', 'you'];
const c = [a,b];
const d = [...a , ...b];
const e = [...a, 'John', ...b];console.log(c); // [["Hi"], ["How", "are", "you"]]
console.log(d); // ["Hi", "How", "are", "you"]
console.log(e); // "Hi", "John", "How", "are", "you"]
Same can be done to get each character from a string as well.
const string = "javascript";
const character = [...string];console.log(string); // "javascript"
console.log(character); //["j", "a", "v", "a", "s", "c", "r", "i", "p", "t"]
With ECMAScript 2015, spread operator makes operations like cloning and merging an object also easy.
const obj1 = {a: 1, b: 2};
const obj2 = {c: 3, d: 4, e: 5};const obj3 = {obj1, obj2};
const obj4 = {obj1, ...obj2};
const obj5 = {...obj1, ...obj2, f: 6}console.log(obj3);// {
obj1: [object Object] {
a: 1,
b: 2
},
obj2: [object Object] {
c: 3,
d: 4,
e: 5
}
}
console.log(obj4); // {
c: 3,
d: 4,
e: 5,
obj1: [object Object] {
a: 1,
b: 2
}
}console.log(obj5);
// {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6
}console.log(obj4);
console.log(obj5);
Cloning:
let obj1 = { a: 1};
let obj2 = { ...obj1};
let obj3 = obj1; console.log(obj2);
// {
a: 1
}console.log(obj3);
// {
a: 1
}obj1.a = 100;console.log(obj2);
// {
a: 1
}console.log(obj3);
// {
a: 100
}
I hope it helps, thanks for reading!