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 much different than in JavaScript. Inside our parentheses we define a comma-separated list of the names of the arguments we want 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 to do some math with them to calculate a total value. When we called the function, we passed in the two values we wanted it to use.
In Chapter 2 we discussed briefly the rules around parentheses in CoffeeScript. I want 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.