Introducing CoffeeScript

Objects

As I wrote above, everything in JavaScript (and, thus, in CoffeeScript) is an object, and every object has properties. (Another way to think about this is to say that everything in JavaScript is a hash, with key-value pairs.) Understanding and working with this can be a bit confusing at first, particularly because of the way the "this" keyword operates. CoffeeScript offers several solutions to this problem, as well as the scoping and variable issues that drive JavaScript programmers crazy.

First, scoping of all variables is lexical and is obvious from the indentation. You can attach variables to the global object, or other objects, but you will end up doing this only when you want, not by mistakenly forgetting to add a "var" somewhere.

Second, properties can be accessed and assigned to as if they were variables, using Ruby-style @varname syntax. So, when you say x=5 in a CoffeeScript program, you're assigning the value 5 to the lexical value x. When you say @x=5 though, you're assigning the value 5 to the property x on the current object.

Finally, "this" is scoped dynamically in JavaScript, changing value to reflect the object to which the current function is attached. This means that if you aren't careful, you can write callback functions that reference "this", but accidentally end up referring to the wrong object. CoffeeScript lets you define functions not only with -> (the "thin arrow"), but also with => (the "fat arrow"). The difference is that when you define functions with =>, they are bound to the value of "this" when it was defined, allowing access to the defining context's properties using @propname syntax.

All of these things come together in CoffeeScript's object model, which extends JavaScript's such that you can work with something resembling a traditional class-instance model, rather than the built-in, JavaScript-style prototype-based model. Prototypes still exist and work—and indeed, CoffeeScript's classes compile into JavaScript prototypes. But, you can get beyond prototype-style inheritance by declaring classes with a constructor. Here is a simple example of the sort of thing you can do:

 class Person     constructor: (firstName='NoFirst', lastName='NoLast') ->         @firstName = firstName         @lastName = lastName         Person.count++      @count: 0  p1 = new Person() console.log p1 console.log Person.count  p2 = new Person('Reuven') console.log p2 console.log Person.count  p3 = new Person('Reuven', 'Lerner') console.log p3 console.log Person.count 

When you run the above file, you get the following output:

 { firstName: 'NoFirst', lastName: 'NoLast' } 1 { firstName: 'Reuven', lastName: 'NoLast' } 2 { firstName: 'Reuven', lastName: 'Lerner' } 3 

This not only shows how you can use CoffeeScript classes in a way similar to traditional classes, but also that you can have default values for function parameters by declaring their values before the -> sign. You also can see how naturally the use of the @propname syntax fits into this object model. The above constructor looks almost like a Ruby method, rather than a JavaScript one, with a clear distinction between local variables and instance variables.

Conclusion

CoffeeScript is an attractive, new language that makes JavaScript programming fun and easy. You can think of it as JavaScript with a new syntax or as an easy-to-learn language that integrates into JavaScript applications, with many ideas taken from Python and Ruby. It removes many of the syntactic bloat and issues associated with traditional JavaScript, simultaneously providing a language that's easier to write and maintain, but also faster to execute, than raw, unoptimized JavaScript. CoffeeScript is a language we all should watch in the coming months and years. It probably won't replace JavaScript altogether, but it definitely will make it easier to accomplish certain tasks.

Next month, I'll look at how CoffeeScript can be integrated into your browser-side Web applications, especially those using jQuery. That's the direction the Ruby on Rails community seems to be moving toward with its 3.1 release, and even if your favorite framework doesn't adopt CoffeeScript, understanding how they work together probably will be useful.

Resources

The home page for CoffeeScript, including documentation, quick references, FAQs and annotated source code, is at http://jashkenas.github.com/coffee-script. There is an active and growing community of CoffeeScript users, with an IRC channel (#coffeescript) and Wiki at GitHub.

For a good introduction to CoffeeScript, see the presentation written by Jacques Crocker, available at http://coffeescript-seattlejs.heroku.com.

Finally, the Pragmatic Programmers have released (at the time of this writing) an excellent pre-release "beta book", written by active CoffeeScript user Trevor Burnham. If you're interested in learning more about this interesting little language, I highly recommend this book. It's mostly aimed at beginners, but given the limited number of advanced CoffeeScript programmers out there, this should not bother you.

______________________

Reuven M. Lerner, Linux Journal Senior Columnist, a longtime Web developer, consultant and trainer,
is completing his PhD in learning sciences at Northwestern University.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Javascript is still alive

Anonymous's picture

Just goes to show that Javascript is still alive.I wonder how much memory it takes to compile from Coffee Script into Javascript.That might be a limiting factor in development.

The setup was confusing. How

Sannomo's picture

The setup was confusing. How would you set this up for testing in a web browser?

Quite bad code formatting for

Anonymous's picture

Quite bad code formatting for a whitespace-aware language.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState