CoffeeScript

CoffeeScript is a beautiful programming language that transcompiles to JavaScript and focuses on brevity and readability.

Basic CoffeeScript

Variables

You don’t need to explicitely declare variables in CoffeeScript:

1
2
3
4
5
6
7
// JavaScript
var message;
message = "Hello World";
alert(message);
// CoffeeScript
message = "Hello World"
alert(message)

Functions

CoffeeScript uses indentation when defining functions and always assumes that the last expression within your function is going to be returned.

1
2
3
4
5
6
7
// JavaScript
var hello = function() {
   return alert("Hello World");
}
// CoffeeScript
hello = ->
  alert("Hello World")

If a given function has parameters you use the notation below:

1
2
3
4
5
6
7
// JavaScript
var say = function(message) {
   return alert(message);
}
// CoffeeScript
hello = (message) ->
  alert(message)

Default parameters are expressed via:

1
2
3
4
5
6
7
8
9
10
11
// CoffeeScript
hello = (message = "Hello World") ->
  alert(message)
// this is the JavaScript that would be generated
var say;
say = function(message) {
  if (message == null){
    message = "Hello World";
  }
  return alert(message);
}

Calling functions in CoffeeScript is as easy as:

1
2
3
4
5
6
// CoffeeScript
hello()
say("Hello World")
say "Hello World"  // We can remove the parentheses
add(1,2)
add 1 2

Since parentheses can be obviated in every function call, a convention exists to remove the parentheses only in the outermost call to improve clarity. For instance, we would use alert say("hello world") rather than alert say "hello world".

String Manipulation

In CoffeeScript you can use string interpolation to insert variables within a string:

1
2
3
4
5
6
// JavaScript
var many = 10;
alert("I drank " + many + " beers yesterday");
// CoffeeScript
many = 10;
alert("I drank #{many} beers yesterday");

More CoffeeScript Syntactic Sugar

  • In CoffeeScript you can use @ to refer to this

Installing CoffeeScript

Via Node.js

  1. Install node.js
  2. Install npm (node package manager)
  3. Install CoffeeScript using npm install -g coffee-script
  4. Verify it has installed correctly coffee -h
  5. To transcompile a CoffeeScript file use coffee -c test.coffee
  6. To transcompile a CoffeeScript file every time the source code is updated use coffee -cw test.coffee
  7. To transcompile all CoffeeScripts files in a folder use coffee -c src -o js
  8. As in 6. you can also use coffee -cw src -o js

In Visual Studio

CoffeeScript Resources

Comments