Rest Operator
A Rest operator can be used in a function in which we are not sure about number of variables that have to be passed.
To make a parameter as a Rest parameter add three periods (...) before the parameter name.
As an example, we can create a function that can accept any number of parameters and find the sum of all the parameters.
import { LightningElement, track } from 'lwc';
export default class restsum extends LightningElement {
connectedCallback(){
console.log(this.sum(1,2,3,4,5,6));//Output is 21
}
//Method to find sum
//It can accept any number of parameters
sum(...restParameters){
return restParameters.reduce((a, b) => a + b, 0);
}
}
The Rest parametes complement Higher Order Functions(Discussed in part 2 of this blog series) and can be used together for plethora of use cases.The Rest operator can also be used to overload functions in Javascript.
For eg we can have a function that only adds 3 numbers.
import { LightningElement, track } from 'lwc';
export default class restsum extends LightningElement {
connectedCallback(){
let a = [1,2,3,4];
console.log(this.sumFirstThree(...a));
//Output would be 6 i.e. sum of first Three
}
sum(a,b,c){
return a+b+c;
}
}
Even if we add 4 or more elemts to the array, the function would only use the first 3 elements and find their sum.Spread Operator
Unlike Rest Operator the spread operator 'spreads' or 'unpacks' collected element into single element. It also uses three periods (...) before the variable name. It can be used for various use cases like
1. Adding elements in between an array
let a = ['apple', 'orange', 'banana'];
let b = ['guava', ...a,
'strawberry'
];
console.log(b);//[ "guava", "apple", "orange", "banana",
"strawberry"
]
2. Copying ArraysTo understand the concept of copying arrays using spread operators consider two examples of copying arrays
Example 1:
let a = ['apple', 'orange', 'banana'];
let b = a;
b.push('blueberry');
console.log(b);//[ "apple", "orange", "banana", "blueberry" ]
console.log(a);//[ "apple", "orange", "banana", "blueberry" ]
If you run the above code in your browser console or in LWC you would observe that both the variables a and b have the same 4 elements! Even though we just added the fourth value to array b. To avoid a situation like this we can use Spread Operator.let a = ['apple', 'orange', 'banana'];
let b = [...a];
b.push('blueberry');
console.log(b);//[ "apple", "orange", "banana", "blueberry" ]
console.log(a);//[ "apple", "orange", "banana"]
As can be seen from the Ouput given in the comments now array b has the 4th element and array a retains its value and has the original 3 elements.