Thursday, June 30, 2011

Exploring CoffeeScript Part 2 - Variables and Functions

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

Tuesday, June 28, 2011

Book Review: Hands-on Node.js

Last week, I finished reading Hands-on Node.js written by Pedro Teixeira. I very much enjoyed reading this concise introduction to Node.js, and although it’s targeted towards beginners, I certainly managed to pick up a few nuggets myself here and there.

After the obligatory introduction, the first chapter opens up with an explanation of why Node.js runs on an event loop and why JavaScript eventually got chosen as the preferred language.

The next chapter shows how to install Node.js on different platforms and also how to get npm up and running.

Chapter 3 discusses the event loop and modules. These first three chapters make up the first part of the book, which provide you with a more theoretical understanding of what Node.js is all about.

The next part of the book contains the chapters that go over the different aspects of the 25 built-in modules that come with Node.js. As the title implies, these chapters contain a lot of code examples and also provide the reader with a good amount of exercises (and also solutions). There are even a chapters that discuss how to debug and unit test Node.js applications.

So, if you want to start out learning about Node.js then this book is your first stop. You can buy the ebook directly from the author for only $ 4.99! Pedro certainly knows his stuff when it comes to Node.js, so this is a real bargain. Also make sure to check out his excellent screencast series on this very topic which are free to watch and download.

Happy learning!

Tuesday, June 21, 2011

Exploring CoffeeScript Part 1 – And Then There Was Coffee

Those of you who have been reading this blog lately know that I’m quite enthusiastic when it comes to JavaScript. As the common behavioral language of the web, JavaScript has been making its way into other aspects of application programming over the last couple of years, notably with server-side frameworks like Node.js and NoSQL databases like CouchDB. I personally find JavaScript to be an awesome programming language, especially when you stick with the good parts. So I’m more than pleased that JavaScript is finally making its way out of the browser to fulfill other purposes as well.

But a couple of months ago I ran into another programming language called CoffeeScript. This neat little language, created by Jeremy Ashkenas, simply compiles its syntax into JavaScript code. In fact, there’s no interpretation of CoffeeScript code at runtime. CoffeeScript essentially builds on top of JavaScript as the core language while adding some syntactic niceties that are heavily inspired by Ruby. The CoffeeScript compiler emits very clean JavaScript code that not only follows best practices but also complies to JSLint without warnings. This all basically means that wherever you can use JavaScript, whether it’s in the browser, on the server-side or for a particular database, you can use CoffeeScript as well. In fact, you can use any JavaScript library right in your CoffeeScript code!

But why should one use CoffeeScript over JavaScript? Well, for starters, the CoffeeScript syntax is much more concise than its JavaScript equivalent. There’s a lot less typing involved for getting the equivalent JavaScript code. Check out this example on the CoffeeScript wiki.

Second, the CoffeeScript language is much richer than JavaScript. It add splats, classes, destructuring assignments and many more small details that makes your code more readable and fun. 

And thirdly, because the creator of Ruby on Rails, David Heinemeier Hansson, says so :-). The upcoming 3.1 release of Ruby on Rails will include CoffeeScript in the box, which means that other web frameworks will probably also add support for CoffeeScript in the future.

Enough with the marketing talk already. Let’s have a quick look at how to get CoffeeScript up and running. For starters, you need to have Node.js and npm installed. Check out the installation guide or Matthew Podwysocki's on how to get Node.js up and running on Windows using Cygwin.

When you have node.js all set up, you can simply use the following command to install the CoffeeScript compiler using npm:

npm install -g coffee-script

Now that we have CoffeeScript installed, we can compile .coffee files into .js files or we can use the interactive REPL. Let’s go for the canonical “Hello Pluto” example here and create a file named hello.coffee with the following code:

console.log 'Hello CoffeeScript'

Notice that we don’t have to provide parentheses here in order to call the console.log function. Next we can use the following command to print the compiled JavaScript directly to our console window:

coffee -p hello.coffee     

or we can use this next command to compile our hello.coffee file to a corresponding hello.js file at the same location in the file system:

coffee -c hello.coffee

The compiled JavaScript output looks like this:

(function() {
  console.log('Hello CoffeeScript');
}).call(this);

You might wonder why the call to console.log is wrapped into a self-executing function. The reason for this is to prevent naming collisions when using our code in conjunction with other JavaScript libraries. You can tell the CoffeeScript compiler to omit this self-executing function by specifying the –b, –bare command-line option.  

We’re also able to keep the CoffeeScript compiler running with the –w, --watch command-line option. This basically lets the CoffeeScript compiler watch for the specified .coffee files and recompile them as soon as they’re changed.

coffee -cw hello.coffee   

So these are the very basics on how to get up and running with CoffeeScript. Expect to see more of the interesting stuff that this amazing programming language has to offer as I’m going to be writing a couple of more blog posts about CoffeeScript. I certainly recommend that you have a decent knowledge of JavaScript before you pick up CoffeeScript. Being able to understand the JavaScript code that is emitted by the CoffeeScript compiler can be crucial at times.

Until next time.

Wednesday, June 15, 2011

Taking Baby Steps with Node.js – The E-VAN Presentation

The recording of my very first E-VAN talk on Node.js is now available. If you want to hear me blabbering on about Node.js then I suggest you have a look.