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?

5
  • 4
    Spread and rest are used in different contexts and a JavaScript parser will be able to know the difference. Commented Aug 14, 2023 at 10:52
  • 5
    it's not an operator but a syntax, which means spread and rest have no overlap Commented Aug 14, 2023 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). Commented Aug 14, 2023 at 10:54
  • @CBroe does javascript parse the three dots as rest only when passed as a function argument? Commented Aug 14, 2023 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. tc39.es/ecma262/multipage/… Commented Aug 14, 2023 at 11:02

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.