skip to Main Content

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


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

    Login or Signup to reply.
  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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search