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:
Arrays:
([firstElement, secondElement]) ->
Results in:
(function(_arg) {
var firstElement, secondElement;
firstElement = _arg[0], secondElement = _arg[1];
});
Objects:
({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;
});Written by Mark Roseboom
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside