Declaring a variable in CoffeeScript is done like this:
The syntax for defining a function in CoffeeScript is an (optional) list of parameters, followed by an arrow and then the function body. In this case, the code for the entire function is put on the same line. Multiple lines are also possible off course, but then the code for the function body needs to be properly indented as the CoffeeScript compiler uses significant whitespace to delimit blocks of code. This is not only for functions, but also for conditions, loops, try/catch statements, etc. … . Also notice that we no longer need to specify any parenthesis for the passed arguments when calling our log function.
Did you notice that the result of the call to console.log is returned to the caller of our log function? CoffeeScript simply returns the last expression of each function by default unless we explicitly use the return keyword.
CoffeeScript also provides a nice and useful keyword in case that we have a function without any parameters that we want to invoke directly.
The first line of code for this example will give us the following compiler error:
TypeError: undefined is not a function
In order to get this code to compile, we need to change this code to the following:
CoffeeScript also supports default parameter values, but this feature is implemented in a different way than what we’ve been used to see to in other programming languages.
In other programming languages, a default value for a parameter is used when a value is omitted in the function call. CoffeeScript takes this a bit further and also uses a default value if null or undefined is explicitly specified in the function call. This might look weird at first, but this also implies that the optional parameters do not have to appear last in the parameter list.
podcast = 'Astronomy cast'
Fascinating language, isn’t it?
There is much more to be said about functions in CoffeeScript, but I will discuss those features in the next couple of blog posts.
Until next time