Quick Intro to CoffeeScript

What is CoffeeScript?

CoffeeScript is a language that compile down into JavaScript. Unlike JavaScript, the code in .coffee file are not interpreted at run time, but are compiled into .js files beforehand . CoffeeScript has gain its popularity because it can be used to implement all capability of Javascript, including Node.js or the browser.

Though there have been debates regarding its practicality, the additional appeal to the community is the elegance and the simplicity through its “syntactic sugar”, which resemble that of ruby and python.

Example Syntax

The best way to see what CoffeeScript is, is to look at some code examples. Obviously, I won’t be able to list out all the syntactical difference between Javascript and CoffeeScript here. However, here is a little taste of how the two differ. Surely, you’ll see some clear differences right away.

Assignment:

var name = "john"; //javascript
name = 'john //coffeescript

Object:

var javascriptObj = {
name: "John",
age: 25,
language: "javascript"
}
coffeescriptObj =
name: 'john'
age: 25
language: 'coffeescript'

Functions:

Simple add function
//javascript
var add = function(num1, num2) {
return num1 + num2;
};
//coffeescript
add = (num1, num2) ->
num1 + num2
function that will log even number between 1- 10
//javascript
var printEven = function(){
for(var i = 0; i < 10; i++){
if(i % 2 === 0){
console.log(i)
}
}
}
//coffeescript
printEven = ->
i = 0
while i < 10
if i % 2 == 0
console.log i
i++
return

If you are interested in seeing some of your own Javascript code turned into CoffeeScript, here is a simple tool for that.

Show your support

Clapping shows how much you appreciated Scott Kao’s story.