Skip to content

Instantly share code, notes, and snippets.

@steckel
Created November 17, 2011 22:31
Show Gist options
  • Save steckel/1374768 to your computer and use it in GitHub Desktop.
Save steckel/1374768 to your computer and use it in GitHub Desktop.
An introduction to CoffeeScript

CoffeeScript

A little language that compiles into JavaScript.

JavaScript is kind of a big deal.

The web was not built for the interactivity we have come to expect of it. Web pages were originally designed to contain static text and images. Hyperlinks were a way to travel between these static pages but, that was the extent of a page's interactivity.

Java and JavaScript emerged as competitors (Java is to JavaScript as Car is to Carpet) in web browsers promising to add a new level of dynamic content and interactivity.

JavaScript grew to be synonymous with "copy and paste" coders adding solar flares and glitter to their animated GIF Geocities page (me, in the 4th grade), and Java retreated to the server side and eventually found it's self inside Google Android.

JavaScript won in the browser but, even though it was hacked together in 10 days and still sucked. "JS had to 'look like Java' only less so, it had to be Java's dumb kid brother or boy-hostage sidekick. Plus, I had to be done in ten days or something worse than JavaScript would have happened." -Brandon Eich (inventor of JavaScript)

In modern web development JavaScript often takes form in Frameworks like MooTools, Prototype.JS, and jQuery which set out to solve many of the problems facing JavaScript including cross browser compatibility, along with a less intimidating learning curve. Ease of use frameworks like these tend to lead to web developers learning to program before they understand the programming language.

With the introduction of NodeJS, JavaScript has recently gotten something it hasn't had before: A stable and consistent environment. When working in NodeJS, the browser stops becoming a wild card variable, and the language is given the opportunity to mature as a general-use programming language. JavaScript is now able to be used on the server side which may eventually compete with Ruby, Python, PHP, and Java (sound familiar?).

  • JavaScript is the programming language of the web.

  • JavaScript is arguably the most popular and widespread programming language.

  • JavaScript is widely misunderstood due to its "bad parts".

  • Most people write JavaScript without understanding JavaScript.

  • JavaScript is gaining momentum as a general-use programming language.

So what the hell is CoffeeScript?

CoffeeScript is a language that aims to give you easy access to "the good parts" of JavaScript. It is an implementation of a major JavaScript syntax redesign with focus on human readability with additional syntax sugar, aliases, and helper features. It is a less verbose version of JavaScript, not a different or simplified language.

CoffeeScript compiles down to JavaScript through it's NodeJS based compiler which it's self is written in CoffeeScript (yo dawg). It also outputs JSLint compliant JavaScript keeping Douglas Crockford at bay (but seriously, he's a fan), and offers you a strict set of guidelines and compiling errors/reporting that is often missed before hitting the browser environment.

Much like when the inventor of JavaScript took initiative to "hack together" JavaScript in under 10 days so there will be a viable competitor to Java for client side programming; Jeremy Ashkenas, creator of CoffeeScript, took initiative to create a "better javascript" because he couldn't simply wait for someone else to do it for him. And like Sarah Conner says, "No fate but what we make." -Terminator II

  • CoffeeScript is "the good parts" of JavaScript with a major syntax redesign.

  • It is a less verbose version of JavaScript, not a different or simplified language.

  • CoffeeScript is to Javascript as Sass is to CSS or Haml is to HTML.

  • The golden rule of CoffeeScript is: "It's just JavaScript".

Why would I want to learn CoffeeScript?

JavaScript has had a hard time being taken seriously up until recently, and has been synonymous with kids copy and pasting code together; hacking away at JavaScript without actually understanding what they are doing.

The time to take the training wheels off is now. With the introduction of NodeJS more pressure for proper design pattern adoption and standard "best-practices" being encouraged is being put on the JavaScript community. Luckily, things like CommonJS modules have been adopted by NodeJS to discourage disposable code and influence cross pollination of traditional software engineers and front end developers.

CoffeeScript also helps developers create high performing JavaScript by keeping it's compiled JavaScript strictly complaint with JSLint. With the introduction of Google's V8 JavaScript engine, which was a huge player in Google Chrome's campaign focusing on it's speed, browser wars have heated up again in a new way: Competing to create the most high performing JavaScript engine. Keeping your code JSLint compliant is a huge component to being able to take advantage of these improvements to the browser environment as they are implemented.

In layman's terms: CoffeeScript makes the transition from copy and paste script kiddy to respected web engineer easier and quicker.

  • CoffeeScript lets you write, and learn, more, good, JavaScript quicker, with greater ease.

  • CoffeeScript's syntax forces strict formatting concepts resulting in better human readability and consistency between developers and teams.

  • It is not CoffeeScript v.s. JavaScript. It is CoffeeScript enhancing the JavaScript programming experience.

  • Major influencers of JavaScript plan to evolve the language to reflect CoffeeScript in the future.

Installing CoffeeScript

With Homebrew (preferred method)

If you don't already have Homebrew, download it; It's awesome. http://mxcl.github.com/homebrew/

  • Open terminal.app

  • Make sure homebrew is up to date $ brew update

  • Install CoffeeScript $ brew install coffee-script

  • Homebrew will take care of installing any dependencies (which in this case means NodeJS).

With Node(JS) Package Manager

If you want to install NodeJS and NPM without Homebrew you can install NodeJS (https://github.com/joyent/node/wiki/Installation) and NPM (http://npmjs.org/)

  • Open terminal.app

  • $ npm install -g coffee-script (g is for global)

TextMate Support

The official CoffeeScript TextMate bundle can be found at https://github.com/jashkenas/coffee-script-tmbundle

  • Open terminal.app

  • $ mkdir -p ~/Library/Application\ Support/TextMate/Bundles

  • $ cd ~/Library/Application\ Support/TextMate/Bundles

  • $ git clone git://github.com/jashkenas/coffee-script-tmbundle CoffeeScript.tmbundle

  • Reopen TextMate or "Reload Bundles" under "Bundles -> Bundle Editor"

Writing CoffeeScript

Think JavaScript without the countless semi-colons and brackets. CoffeeScript uses whitespace (or indenting) to define blocks of code. You also don't need to use parentheses to invoke a function when passing arguments or use the keyword var when declaring variables. The keyword function has also been replaced by ->.

Basic CoffeeScript Syntax

Let's convert a simple jQuery click method implementation from JavaScript to CoffeeScript:

Convert Simple JavaScript to CoffeeScript

example.coffee -> examples.js

CoffeeScript

Compile the CoffeeScript using the terminal.app coffee -c example.coffee

Compiled JavaScript Rendered JavaScript

A few CoffeeScript features

  • Heredocs Heredocs

  • String Interpolation String Interpolation

  • If, Else, Unless, and Conditional Assignment:
    Conditional Statement

  • Array Comprehensions:
    Array Comprehensions

  • The Existential Operator
    The Existential Operator

  • Classes
    Classes

  • Operators and Aliases:
    CoffeeScript.........JavaScript
    is..........................===
    isnt.......................!==
    not........................!
    and........................&&
    or..........................||
    true, yes, on......true
    false, no, off.....false
    @, this.................this
    of..........................in
    in..........................no JS equivalent

  • as well as improved Object and Array syntax, Function Binding (=>), Splats (...), Slicing and Splicing with Ranges (..), Cake/Cakefiles, and more...

Compiling CoffeeScript:

Like Compass or Sass, you'll be compiling your CoffeeScript files to JavaScript with the terminal.app. Here are some methods of compiling:

  • Compile example.coffee to example.js coffee -c example.coffee

  • Watch a file and continue to re-compile it as it's updated coffee -cw example.coffee

  • Watch a folder of CoffeeScript files and compile them to a folder of JavaScript files coffee -co javascripts/ coffeescripts/ (-cwo works too)

  • Compile and combine CoffeeScript files into a single JavaScript file coffee -j javascripts/app.js -c coffeescripts/*.coffee (my favorite)

Coffee in the terminal

Coffee is also available in the terminal in more ways than simply a compiler.

  • Error reporting
  • There is a REPL available in terminal.app by simply typing coffee
  • Cakefiles (CoffeeScript's version of Makefiles or Rakefiles)
  • Shell scripting

CoffeeScript in the terminal

What do the pros think?

"It helps to have things like CoffeeScript out there it isn't overriding, it doesn't tell us what we must do but its suggestive, and if we want to pave that cow path we can, and I'm in favor."

-Brendan Eich (The creator of Javascript)

"I think CoffeeScript is clearly good stuff. CoffeeScript is elegant it sort of takes the good parts, removes all of the stupid awful syntax that were inherited from the wrong languages, replaces it with something that is small and elegant and expressive. CoffeeScript is really great. And CoffeeScript is having a big influence on the ECMA Script committee... CoffeeScript is definitely in the right direction and I would like to see future languages looking more like CoffeeScript than like C."

-Douglas Crockford (Inventor of JSON and JSLint among other JavaScript best practices and general bad assery)

Opposition

While this write up's focus is more of an introduction to CoffeeScript rather than an evangelist's plea for everyone to adopt it, I will respond to a few opinion's I've heard on opposition to CoffeeScript.

  • CoffeeScript doesn't let me do anything I can't already do in JavaScript

I actually believe this is one of CoffeeScript's strong points. Using CoffeeScript as a tool to write, and learn, more, good, JavaScript quicker, with greater ease, is the goal. Telling people that they cannot write amazing JavaScript without CoffeeScript is foolish.

There might even be some people who pick up CoffeeScript for a short period of time to learn how it compiles, and then drop CoffeeScript once they have learned its suggested JavaScript implementations. However, these types of JavaScript developers probably already have done this with JSLint so they may not need CoffeeScript. Which brings me to my next point of opposition...

  • Why do I need so many aliases and shortcuts? Do people have trouble spelling function or var? I know how to write for loops like the back of my hand and other developers should learn it too if they want to be a professional.

While this is an interesting point, I don't think it's a proper argument against people who wish to benefit from CoffeeScript's ease of use. The best code you can write, is the code you don't have to. By creating tons of shortcut methods that cut down on your key strokes and boilerplate code, you're not simply making it easier for people who have trouble with spelling and memory (people like me) but, you're cutting down the room for human error.

The argument is similar to a mechanic complaining how much he dislikes working with fuel injection because he enjoys utilizing his expert knowledge in fine tuning carburetors for high performance. Just because you're good at doing something the long and hard (that's what she said) way, doesn't mean you should have to.

Links and References

Projects using CoffeeScript

More information on learning CoffeeScript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment