Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I skip parameter assignments in a function signature?

With array destructuring, it's possible to discard leading items by inserting commas without a preceding reference:

const [ , two ] = [ 1, 2 ]

The same isn't true of function signatures — the following code won't parse because the leading comma in the signature is unexpected:

function ditchFirstArgument( , second ){}

Why do I need to provide references for leading parameters in ES6 function expressions?

like image 417
Barney Avatar asked May 14 '16 16:05

Barney


1 Answers

Roman's insight from Go is useful but inappropriate to JS where the token _ is a valid reference, conventionally used by the Underscore and later Lodash libraries.

Even if that's acceptable, you'd have to create and avoid dud references for every unused argument, which isn't ideal.

However, it is possible to destructure a function argument into an empty object, which effectively nullifies the parameter without reference.

function take_third( {}, {}, third ){
  return third 
}

EDIT: As Paul points out in the comments, this will throw if any of the skipped parameter values are null or undefined. undefined values can be guarded against with default assignments, but this won't work for null:

function take_third( {} = {}, {} = {}, third ){
  return third 
}
like image 70
Barney Avatar answered Sep 22 '22 12:09

Barney