search

Home  >  Q&A  >  body text

How to differentiate between spread operator and remainder operator in JavaScript?

<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>
P粉022501495P粉022501495448 days ago488

reply all(2)I'll reply

  • P粉545910687

    P粉5459106872023-09-05 10:12:18

    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.

    reply
    0
  • P粉549412038

    P粉5494120382023-09-05 09:23:13

    ... is not an operator. It is the main syntax, just like () in the for statement (they are part of the for 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:

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

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

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

    ...it's obviously expansion, not remainder, since you use it in array literals (1), object literals (2), and parameter lists of function calls (3).

    reply
    0
  • Cancelreply