Episode 5: Rest Parameters & Spread Syntax (…) | LWC Salesforce ☁️⚡️



 The rest parameter syntax allows a function to accept n number of arguments as an array, collect it in a single parameter and use it accordingly. 

For example let’s suppose you are creating a sum function, but you don’t want to limit the numbers of parameters in it. Yes you should use Rest Parameters there, let’s understand it using a simple example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function sum(...theArgs) {
  let total = 0;
  for (const arg of theArgs) {
    total += arg;
  }
  return total;
}

console.log(sum(1, 2, 3));
// expected output: 6

console.log(sum(1, 2, 3, 4));
// expected output: 10

Few important things to remember while using rest parameters

A function definition's last parameter can be prefixed with (...)(three FULL STOP characters), which will cause all remaining (user supplied) parameters to be placed within a standard JavaScript array. Only the last parameter in a function definition can be a rest parameter.

Now that you understand how rest parameters work, here's a question: What do you think this code prints to the console?

1
2
3
4
let array1 = ['one', 'two'];
let array2 = ['three', 'four'];
array1 = [...array1, ...array2];
console.log(...array1);  

Did you guess, "one","two","three","four"? If you did, then you understand how the spread operator works. Yes you heard me right this is an example of Spread Operator

The three dots (...) operator has two uses. As the rest operator, it is used to gather up all the remaining arguments into an array. But as the spread operator, it allows an iterable such as an array or string to be expanded in places where zero or more arguments or elements are expected. It is just either expanding or collapsing that iterable.

Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements into a single element. 

If you like to learn more about how spread and rest works, do checkout official documentation below.

Rest Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

Spread Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax


Checkout complete video tutorial below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments