javascriptarraysecmascript-6spread-syntaxrest-parameters

How does JavaScript know the difference between the spread and rest operator?


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?


Solution

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