How to differentiate between spread operator and remainder operator in JavaScript?
P粉022501495
2023-09-04 11:25:07
<p>The syntax is the same, so how does JavaScript distinguish between the two under the hood? </p>
<p>Is it judged based on the data type of the variable being operated on? Or is it based on where the variable is used? Or neither? </p>
The JavaScript parser determines this by analyzing the grammatical context in which the three dots appear.
It will consider whether these 3 points are used with array literals, function calls or function parameters.
For spread operator: When 3 dots are used in array literals and function calls, it is considered a spread operator.
For Remaining Parameter Operator: When 3 dots are used in the parameters of a function definition, it is considered as the remaining parameter operator.
...
is not an operator. It is the main syntax, just like()
in thefor
statement (they are part of thefor
syntax, not instances of the grouping operator) . Operators don't work like spread and rest syntax.The parser knows which one you are using because of the position in which you are using it, because only one of each position is valid and the other is invalid. For example:
...it's obvious that you are using remainder syntax in both cases, since it is used in destructuring patterns (1 and 2) and in argument lists (3).
And for:
...it's obviously expansion, not remainder, since you use it in array literals (1), object literals (2), and parameter lists of function calls (3).