Arguments
Just like in JavaScript functions in CoffeeScript can also take arguments. Arguments let us pass objects into the function so that the function can then perform calculations, data manipulation, or whatever our little hearts desire.
In CoffeeScript defining a function that takes arguments is not too much different than in JavaScript. In between our parentheses we define a comma separated list of the names of the arguments we would like the function to accept.
Example: (source: function_with_args.coffee)
calculateTotal = (sub_total, rate) -> tax = sub_total * rate sub_total + tax console.log calculateTotal(100, 0.0625)
Example: (source: function_with_args.js)
(function() { var calculateTotal; calculateTotal = function(sub_total, rate) { var tax; tax = sub_total * rate; return sub_total + tax; }; console.log(calculateTotal(100, 0.0625)); }).call(this);
Output: (source: function_with_args.coffee)
106.25
As you can see in our example we defined our function to take in two arguments and do some math with them to calculate a total value. When we called the functions we passed in the two values we wanted it to use.
In Chapter 2, “The Basics” we discussed briefly the rules around parentheses in CoffeeScript. I would like to take this time to reiterate one of those rules. Because our function takes arguments we are allowed to omit the parentheses when calling the function. This means we could also write our example like this:
Example: (source: function_with_args_no_parens.coffee)
calculateTotal = (sub_total, rate) -> tax = sub_total * rate sub_total + tax console.log calculateTotal 100, 0.0625
Example: (source: function_with_args_no_parens.js)
(function() { var calculateTotal; calculateTotal = function(sub_total, rate) { var tax; tax = sub_total * rate; return sub_total + tax; }; console.log(calculateTotal(100, 0.0625)); }).call(this);
Output: (source: function_with_args_no_parens.coffee)
106.25
As you can see CoffeeScript correctly compiled the JavaScript for us, putting those parentheses back where they are needed.