Using a rest parameter before the last parameter in function definition

My problem is best explained with a simple code example:

function doThing(a, ...b, c) { console.log(a, b, c) } doThing(1,2,3,4); // Expect "1 [2,3] 4"

This instead gives a syntax error Unexpected token, pointing to the comma after the b in the function definition.

Is it not possible to put a single parameter after a 'rested' parameter with ES6? If not, any idea why? It would be really useful for me. Thanks!

Edit: I initially thought that doThing(a, ...b, c) would be completely unambiguous, but I see now that doThing(1,2,3) would need an arbitrary rule to decide whether the 3 goes in b or c (i.e. if we pass a number of params that is less than or equal to the number of params in the function definition).

-------------Problems Reply------------

  1. You should not use js keywords in function names (e.g. do)
  2. As developer.mozilla.org site says:

If the last named argument of a function is prefixed with ..., it becomes an array whose elements from 0 to theArgs.length are supplied by the actual arguments passed to the function.

Actually this feature of ES6 is called Rest parameters so it is meant to be the last in the list of parameters.

So this code will work:

function do2 (a, b, ...c) {
console.log(a, b, c);
}
do2(1,2,3,4);

Category:javascript Views:0 Time:2018-05-12

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.203 (s). 11 q(s)