Let's start this lesson with some explanation.
In all the previous lessons of this section,
I did not tell you the whole truth about the
operator ...
In fact, this operator, depending on the place in the code, can be called either the spread operator or the rest operator.
As you already know, when the spread operator
is placed in front of an array or string, it
separates them into individual values. The
rest operator, although it has the same syntax
in the form ...
, is meant for something else.
Now let's figure out why. Let's say we have a function that takes two parameters:
function func(a, b) {
console.log(a);
console.log(b);
}
You should already know that if you pass extra parameters to a function, this will not lead to an error:
func(1, 2, 3, 4, 5);
The operator rest
allows you to
get all the extra parameters as an array.
To do this, one more parameter is added
to the function (necessarily the last one),
before which 3
dots are written:
function func(a, b, ...rest) {
}
These three dots are the rest operator,
and the name of the variable can be any
name, but it is also common way to call
it rest
.
Let's call our function with an excess
number of parameters and see what goes
into the parameters a
and b
,
and what goes into the remainder rest
:
func(1, 2, 3, 4, 5);
function func(a, b, ...rest) {
console.log(a); // shows 1
console.log(b); // shows 2
console.log(rest); // shows [3, 4, 5]
}
If there are no extra parameters, then
an empty array will be written to the
variable rest
:
func(1, 2);
function func(a, b, ...rest) {
console.log(a); // shows 1
console.log(b); // shows 2
console.log(rest); // shows []
}
A function may have no parameters at all,
but you can add rest
to it. In
this case, the function can be called
with any number of parameters, and all
of them will fall into the
rest
array:
function func(...rest) {
console.log(rest);
}