The syntax is identical so how does JavaScript distinguish the two under the hood?
Does it look at the data type of the variable that is being operated on? Or where that variable is being used? Both or neither?
The syntax is identical so how does JavaScript distinguish the two under the hood?
Does it look at the data type of the variable that is being operated on? Or where that variable is being used? Both or neither?
2
Answers
...
isn’t an operator. It’s primary syntax, like the()
in afor
statement (which are part of thefor
syntax, not an instance of the grouping operator). Operators can’t do what spread and rest syntax do.The parser knows which you’re using because of where you use it, since each is only valid in a place the other isn’t valid. For instance, with:
…it’s clear you’re using rest in both cases because it’s being used in destructuring patterns (1 & 2) and a parameter list (3).
Whereas for:
…it’s clearly spread, not rest, since you’re using it in an array literal (1), an object literal (2), and the argument list of a function call (3).
JavaScript parser determines by analyzing the syntactic context in which three dots appears.
It takes into account whether these 3 dots used with an array literals, function call or function parameter.
For Spread operator:- When 3 dots used within an array literals and in function call then it is treated as Spread operator.
For Rest operator:- When 3 dots used within the parameters of a function definition then it is treated as Rest operator.