skip to Main Content

I keep coming across this syntax and I’m having trouble understanding exactly what it’s doing:

export class SomeClass extends SomeParent {
    constructor(...[configuration]) {
        // lines of code that reference only "configuration"
    }
}

Playing around in the Node REPL I can’t find a difference between:

function foo(...[bar]) { console.log(bar); console.log(arguments) }

…and…

function foo(bar) { console.log(bar); console.log(arguments) }

…so what is it for?

2

Answers


  1. The first snippet, with the …[bar] syntax, explicitly extracts the first element of the passed array and assigns it to the variable bar. This can be useful when you know the array will contain only one element and you want to work with that element directly.

    The second snippet, without the spread syntax, treats the passed argument(s) as regular function parameters. If you call foo(123, 456), bar will receive the value 123, and the arguments object will contain both 123 and 456.

    However, note that the use of arguments here is somewhat misleading. In modern JavaScript, the arguments object is not available inside arrow functions or functions defined using the ES6 function syntax. It’s worth mentioning that the use of arguments is generally discouraged due to its complexities and the availability of rest parameters and spread syntax.

    Login or Signup to reply.
  2. It seems pretty pointless indeed. You’ll need to ask the author of the code what they intended with this, they should at least have left a comment.

    However, there actually is a minuscule difference: rest parameters do not count for the function’s arity. So (function(bar){}).length is 1, whereas (function(...[bar]){}).length is 0.

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