A quick introduction to CoffeeScript

As we near the end of our high-level summaries of the basic software tools used by modern-day web developers, here in our Intro to web and mobile app development series we'll introduce you to a magnificent, fun-to-write, meta-level, and transcompiling language (i.e. converts to one language from another) called CoffeeScript.

[Author's note: I wrote the first couple dozen tutorials in this series a few years ago and I'm in the process of updating the content to reflect the evolution of best practices in the industry. Please comment if you see anything I missed that should be updated. Thanks!]

As described succinctly on their website, CoffeeScript is:

…a little language that compiles into JavaScript. Underneath all those awkward braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

In other words, CoffeeScript helps make writing JavaScript less painful. In fact, CoffeeScript helps you write better JavaScript, is gracious because it adds semicolons for you, and often compiles into JavaScript than runs faster than if you write it manually.

We recommend learning CoffeeScript for beginning Ruby on Rails developers from the get-go — alongside JavaScript — because CoffeeScript's syntax is more similar to Ruby and, practically speaking, it's easier to read and write less code when learning.

What does CoffeeScript look like?

Here's a great example from their website:

# Assignment:
number   = 42
opposite = true
# Conditions:
number = -42 if opposite
# Functions:
square = (x) -> x * x
# Arrays:
list = [1, 2, 3, 4, 5]
# Objects:
math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x
# Splats:
race = (winner, runners...) ->
  print winner, runners
# Existence:
alert "I knew it!" if elvis?
# Array comprehensions:
cubes = (math.cube num for num in list)

Having written a ton of web apps using Ruby on Rails with CoffeeScript now, I can confirm that it's worth learning. Visit the CoffeeScript website to see what the above code translates into (and how many lines of code you save!).

Tip: I use the site js2coffee.org often to convert back and forth between CoffeeScript and JavaScript. I'd recommend taking a moment to get a feel for CoffeeScript over there now.

- — -

In our next post we'll take a quick look at XML and JSON. Previous post: Git Intro.


Share this article

LinkedIn Reddit

Startup Rocket

We help entrepreneurs ideate, validate, create, grow, and fund new ventures.

Based on decades of startup experience, our team has developed a comprehensive operations framework, a collaborative online tool, and a personalized coaching experience to help take your business to the next level.

We'll email you as soon as more spots become available in our private beta.