30 Jun
2011

Exploring CoffeeScript Part 2 – Variables and Functions

Category:UncategorizedTag: :

As I mentioned in the previous blog post, CoffeeScript is a neat little language that compiles down to JavaScript code. Its syntax is heavily inspired by Ruby and next to bringing a lot of nice language features to the table, it also requires less amount of code than writing the equivalent directly in JavaScript. For this blog post, we?ll dive into some of this syntactic sugar by discussing variables and functions.

Variables

Declaring a variable in CoffeeScript is done like this:

podcast = 'Astronomy cast'

There?s no need to use the var keyword like in JavaScript. In fact, using the var keyword results in a compiler error. We also don?t need to provide a semi-colon at the end of the statement. These are added automatically for you during compilation. When we omit semi-colons in JavaScript, the engine also tries to add them at runtime but this behavior can cause a lot of grief. CoffeeScript correctly adds them for us, and although we no longer need to type in semi-colons, we?re still able to do so if we want to.

The variable declaration from above translates into the following JavaScript:

(function() {
  var podcast;
  podcast = 'Astronomy cast';
}).call(this);

The resulting code here is actually quite interesting. When we want to declare a local variable in JavaScript and we forget to specify the var keyword, then this variable ends up becoming a global variable instead.

/*var*/ f  = 'fubar';
console.log(window.f);    // Outputs 'fubar'

This can no longer happen just by accident when using CoffeeScript as it wraps all generated JavaScript in a self-executing function and by automatically emitting the var keyword before the variable name. We?re still able to create global variables but the only way is to declare them explicitly.

window.f = 'fubar'

The use of global variables is strongly discouraged when using JavaScript. As a result, the same goes for CoffeeScript as well.

Functions

The tedious function keyword in JavaScript is not part of the CoffeeScript syntax. Instead it uses an arrow to define a function.

log = (message) -> console.log message
log 'Podcast downloader 2000'

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.

The code for this simple example is translated into the following JavaScript code:

var log;
log = function(message) {
    return console.log(message);
};

log('Podcast downloader 2000');

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.

do -> console.log 'Podcast downloader 2000'

The do keyword just executes a function directly without having to assign it to a variable and invoke it on the next line. The resulting JavaScript code is a call to console.log wrapped in a self-executing function:

(function() {
    return console.log('Podcast downloader 2000');
})();

In JavaScript we have both function expressions and function declarations. You can read this blog post to learn more about both these concepts. CoffeeScript only supports function expressions.

download 'Astronomy cast'

download = (podcast) -> 
    console.log podcast

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:

download = (podcast) -> 
    console.log podcast
    
download 'Astronomy cast'

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.

download = (podcast = 'Astronomy Cast') ->
    console.log podcast

download 'Hardcore history'        # Outputs 'Hardcore history'
download()                         # Outputs 'Astronomy Cast'
do download                        # Another way of calling download, but without ()
download null                      # Still outputs 'Astronomy Cast'
download undefined                 # Still outputs 'Astronomy Cast'

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.

foo = (arg1 = 'default1', arg2 = 'default2', arg3 = 'default3') -> 
    ...
    
foo null, 'not_default', null

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

One thought on “Exploring CoffeeScript Part 2 – Variables and Functions”

  1.  I am Very thank full the owner of this blog. Because of this blog is very informative for me.. And I ask u some thing You make more this type blog where we can get more knowledge.
    Thanks you very high work..

    CRM tools

Comments are closed.