1

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Jennifer
  • 13
  • 3
  • 4
    Spread and rest are used in different contexts and a JavaScript parser will be able to know the difference. – evolutionxbox Aug 14 '23 at 10:52
  • 5
    it's not an operator but a syntax, which means spread and rest have no overlap – Max Aug 14 '23 at 10:52
  • 1
    Rest _parameter_ syntax comes into play, when you _define_ a function argument, for example, `function sum(...theArgs)`. Spreading comes into play, when you _pass_ an argument somewhere, `sum(...numbers)`. – CBroe Aug 14 '23 at 10:54
  • @CBroe does javascript parse the three dots as rest only when passed as a function argument? – GrafiCode Aug 14 '23 at 10:56
  • 2
    @GrafiCode the specification of rest parameter syntax is part of "15 ECMAScript Language: Functions and Classes, 15.1 Parameter Lists", so it is limited to that kind of context to begin with. https://tc39.es/ecma262/multipage/ecmascript-language-functions-and-classes.html#sec-parameter-lists – CBroe Aug 14 '23 at 11:02

2 Answers2

3

... isn't an operator. It's primary syntax, like the () in a for statement (which are part of the for 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:

// 1
const [first, ...rest] = someArray;
// 2
const { a, ...others } = someObject;
// 3
function example(p1, ...others) {
    // ...
}

...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:

// 1
const x = [...someIterable];
// 2
const o = { ...someObject };
// 3
example(...someIterable);

...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).

VLAZ
  • 26,331
  • 9
  • 49
  • 67
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

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.