REST PARAMETERS AND THE SPREAD OPERATOR
It can be very useful for a function to accept any number of arguments. For example, Math.max computes the maximum of all arguments it is given
But how can we write such a function
well
the answer is rest parameter
look at this code:
function max(...numbers) {
let result = -Infinity;
for (let number of numbers) {
if (number > result) result = number;
}
return result;
}
console.log(max(4, 1, 9, -2));
// → 9
in the above example the number argument contains all the value as an array (i,e. [4,1,9,-2]) , and it is our rest parameter.
a rest parameter takes extra arguments and hold them in an array.And the triple dot(...)
sign is called our spread operator.
for example:
function restParameter( num1, num2, ...remainingArguments ){
console.log(remainingArguments);
}
restParameter(1,4,8,2,4); // -> [8,2,4]
restParameter(3,4,5,2,1); // -> [5,2,1]
when such a function is called the rest parameter holds all the remaining values. but, in case there are other parameters before it, their values are not part of that array.
when as in max,it is the only parameter, it will hold all arguments.
You can also use a similar three-dot notation to call a function with an array of
arguments. The spread operator pass each elements as separate arguments to the function.
let numbers = [5, 1, 7];
console.log(max(...numbers));
// → 5 1 7
Thank you for reading my blog...
have any doubt then please comment below...
Great quality content bro keep it up
ReplyDeleteउत्कृष्ट भाईजान
ReplyDeletehttps://navodayaboyquotes.blogspot.com/?m=1
धन्यवाद् सर
Delete🙏👍👍👍👍
ReplyDelete😉😉
Delete