coffeescript

For some of us who’ve been programming JavaScript since it’s early days in the 1990’s, it’s hard to understand why we should learn yet another programming language, and one which converts into JavaScript which we already know.

The idea with CoffeeScript they say is an attempt to expose the good parts of JavaScript in a simple way.

From my testing with Coffeescript, the real advantage I see is in the readability afterwords. It takes less than half the time to figure out what code is doing and jump right back into it. Maintainability is really important when it comes to choosing a programming language to use.

On the main page, they’ve got a really nice example that show’s how much simpler Coffee script can be to write and to understand after it’s written.

CoffeeScript:

# 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)

Compiled JavaScript:

var cubes, list, math, num, number, opposite, race, square,
  slice = [].slice;

number = 42;

opposite = true;

if (opposite) {
  number = -42;
}

square = function(x) {
  return x * x;
};

list = [1, 2, 3, 4, 5];

math = {
  root: Math.sqrt,
  square: square,
  cube: function(x) {
    return x * square(x);
  }
};

race = function() {
  var runners, winner;
  winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : [];
  return print(winner, runners);
};

if (typeof elvis !== "undefined" && elvis !== null) {
  alert("I knew it!");
}

cubes = (function() {
  var i, len, results;
  results = [];
  for (i = 0, len = list.length; i < len; i++) {
    num = list[i];
    results.push(math.cube(num));
  }
  return results;
})();

News Reporter
Hi there. I'm part of the staff here at onkea eLearning company working hard to create some tutorials and answer your support questions.

Leave a Reply

Your email address will not be published. Required fields are marked *