0

Does Javascript/ES8 have shorthand argument names, like Swift?

eg. arr.sort { $0.name > $1.name }

James
  • 317
  • 2
  • 15
  • 3
    There's no such thing as ES8. If you mean modern ES editions, they are covered by 'Javascript', and proposals are referred as ES.next. JSX tag looks irrelevant here, and I would suggest to add Swift tag since it's essential for understanding the main point. – Estus Flask Jun 15 '17 at 09:05
  • Btw, [that's not a usable comparison function anyway](https://stackoverflow.com/q/24080785/1048572) – Bergi Jun 15 '17 at 10:52

2 Answers2

2

There are no shorthand arguments in Javascript. The closest alternatives are arguments and ES6 rest parameter.

function fn(param1, param2) {
  const $ = arguments;

  // by name
  console.log(param1, param2);

  // by order
  console.log($[0], $[1]);
}

Rest parameter it is more consistent than arguments, the latter isn't supported in arrow functions:

const fn = (...$) => {
  // by name
  let [param1, param2] = $;
  console.log(param1, param2);

  // by order
  console.log($[0], $[1]);
}

Notice that $ parameter name is used to draw an analogy to Swift. It is not recommended to use $ name in practice because it may be confused with conventional jQuery $ variable. The conventional meaningful name for rest parameter that includes all arguments is args.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • I would change `...$` to something like `...args` makes it easier to read. Otherwise, great answer! – Mr. Baudin Jun 15 '17 at 09:12
  • `let { param1, param2 } = $;` should be `let [ param1, param2 ] = $` because `rest` operator returns an `Array`. But the point is: `OP` was about shorthand arguments not something similar. – Hitmands Jun 15 '17 at 09:14
  • @Mr.Baudin Thanks. $ is used solely to draw an analogy with Swift. `args` is by far more conventional and convenient. – Estus Flask Jun 15 '17 at 09:16
  • @estus I understand and you are right ofc. Just wanted to add the comment to give a more "javascripty" way of naming the parameter. "I would change" was not directed to your answer so much as to the general idea of the solution. - I should have written a better comment. Great answer and sorry for the mixup. – Mr. Baudin Jun 15 '17 at 09:19
1

No, javascript doesn't support shorthand argument name.

Hitmands
  • 13,491
  • 4
  • 34
  • 69