Last Updated: July 16, 2021
· mroseboom

Expansive Argument Handling

CoffeeScript provides an excellent syntax for handling a wide range of scenarios for expected function arguments. Here are some examples of a few (some more known than others).

Splats: Allows you more control of a function's arguments when there could an uncertain amount of parmeters passed:

(first, others..., last) ->

The first and last arguments will be stored in there respective variables, and all arguments in between those two will be stored as an array in the other variable.

Splats are covered in the CS documentation, but less known are handling function arguments of different object types. The below functions are all valid CS:


([firstElement, secondElement]) ->

Results in:

(function(_arg) {
  var firstElement, secondElement;
  firstElement = _arg[0], secondElement = _arg[1];


({firstKey, secondKey}) ->

Results in:

(function(_arg) {
  var firstKey, secondKey;
  firstKey = _arg.firstKey, secondKey = _arg.secondKey;

Instance Variables:

(@firstObjectVariable, @secondObjectVariable) ->

Results in:

(function(firstObjectVariable, secondObjectVariable) {
  this.firstObjectVariable = firstObjectVariable;
  this.secondObjectVariable = secondObjectVariable;