Navigation

A taste of CoffeeScript (part 1)

By Sara Vieira | JavaScript, Web Development | May 21, 2013

Let’s face it, JavaScript hasn’t always had the best reputation among developers, and since the foundation of CoffeeScript back in 2009 this little language has taken the world of JavaScript developers by storm; mainly because it overcomes what some may say is the worst aspect of JavaScript: the syntax of its code.

Even though this is a new language you will pick it up really fast mainly because it’s reformulated JavaScript; it’s essentially prettier, simpler JavaScript .

When writing CoffeeScript don’t forget you are writing code that before being deployed is going to be compiled into JavaScript that follows best practices and passes the JSLint test, so that’s one less thing you have to worry about. The output will still be valid JavaScript that the browser will not have a problem in reading. CoffeeScript is to JavaScript what SASS is to CSS: a way to write simpler and more productive code.

 

Installing and using

CoffeeScript is a node.js utility so in order to install it you need to have node.js installed as well as the node package manager. Assuming that you have installed these two packages all you need to do is go to your terminal and install CoffeeScript with the package manager using the code:

npm install -g coffee-script

Just with that you have CoffeeScript installed on your machine. In order to compile a .coffee file into a JavaScript file you need to type:

coffee --compile script.coffee

This will compile the file script.coffee into script.js in the same directory but will only do it when you run the command, if you want it to compile in every change you make in the coffee file you need to add the –watch before the compile:

coffee --watch --compile script.coffee

With this added your JavaScript will be compiled every time you make a change to your .coffee file.

 

Variables

When writing a JavaScript variable we have to prepend the var keyword, with CoffeeScript that keyword is gone and you can just type out the variable and assign it to something. Another thing to look out for is that CoffeeScript uses a lot of indentation methods to avoid semi-colons and for the language to understand that the variable statement is complete you just need to move to a new line:

age = 21
country = "Portugal"

In JavaScript you would have to type something like:

var age = 21;
var country = "Portugal";

It’s a small example but you can begin to see how powerful CoffeeScript is when it comes to simplifying your code.

 

Logical and comparative operators

Remember all that time you spent memorizing JavaScript operators? Remember wondering why you needed to use === instead of just using is? Well CoffeeScript also takes care of that. It offers some really nice aliases for the operators:

Comparison operators

  • === can now be traded for simply is;
  • !== is equally transformed to the more readable isnt.

Logical operators

  • Instead of using && you can just use and;
  • as for || from now on you can type or;
  • the little exclamation point that stated a not is switched for the most logical thing: not.

 

If statements

Another thing CoffeeScript gets rid of is curly braces. It uses the indenting method to declare when you are inside a statement, if statements work like JavaScript but you don’t need the curly braces or the parenthesis; just indent the code you wish to run when the statement is true:

if work > 24 and sleep < 8
   vacations()
else 
   work()

will compile into JavaScript as:

if (work > 24 && sleep < 8) { 
 vacations();  
} else {  
    work();
} 

I hope that you are starting to see the benefits of CoffeeScript just with these simple demonstrations of how clean it can make your code, and cleaner code means more maintainable code.

 

Looping through arrays

Looping through arrays is one of the things you are bound to do in every JavaScript app you write and the syntax for looping through them in JavaScript isn’t the simplest or the cleanest, I think this is where CoffeeScript really shines. To loop through an array we use a for..in loop , like so:

tasks = ['Design','Code','Groceries']  
for task in tasks  
 alert task

All this piece of code will do is read all the things in the array and then alert then one by one, just to make things even simpler you can even write the for…in loop in one line, like so:

tasks = ['Design','Code','Groceries']  
alert task for task in tasks  

It’s simply far more readable and maintainable than the vanilla JavaScript, speaking of which the code produced by CoffeeScript for those two lines would be:

var task, tasks, _i, _len;

tasks = ['Design', 'Code', 'Groceries'];

for (_i = 0, _len = tasks.length; _i < _len; _i++) {
  task = tasks[_i];
  alert(task);
}

 

While loops

While loops are also very useful when constructing your JavaScript app and CoffeeScript doesn’t fail to make this easier to read and write as well, for example:

while sleep < 8
   sleep()

Or you can write it all on one line if you prefer:

while sleep < 8 then sleep()

Or:

sleep() until sleep > 8

In pure JavaScript this would translate to:

//then
while (sleep < 8) {
  sleep();
}

Or:

//until
while (!(sleep > 8)) {
  sleep();
}

 

Functions

Functions are also another vital part of any programming language and even though functions in JavaScript aren’t as messy as some other parts CoffeeScript simplifies this to the max as well, a simple function that takes someone’s name and then alerts it can be written like this:

sayHi = (name) -> 
 return "Hello " + name
alert sayHi('Sara')

All you do is name the function, in this case the functions is called sayHi, and then after the equal sign you need to specify the parameters. Here name is the single parameter, after the base of our function is defined we need to type -> followed on the next line by what we want the function to do so that CoffeeScript knows we are inside the function. In this case all I want it do is return “Hello” and then the name of the person and lastly I use a simple alert to call the function with the name. We can also write this in one line eliminating the enter and indenting just by writing what the function will do after the -> :

sayHi = (name) -> return "Hello " + name

This little snippet of code will be compiled into the following JavaScript:

var sayHi;

sayHi = function(name) {
  return "Hello " + name;
};

alert(sayHi('Sara'));

Of course this was a really simple function but as you can see it saved us 3 lines of code and of course in the JavaScript we could just name the variable as we declare the function like so:

var sayHi = function(name) {
  return "Hello " + name;
};

alert(sayHi('Sara'));

The examples I have given here are what CoffeeScript compiles to and even though in most instances there are easier ways to type something out, all the JavaScript compiled is valid and semantic.

 

Conclusion

This is just the beginning of what CoffeeScript can give you, when things start getting more complex this little language will give you a lot of leverage when compared to JavaScript, less code you need to write , more human readable code, and more maintainable as well, so that you can come back to a website a year later and know what is going on in that JavaScript.

Stay tuned for the second part of this series where I will show you how to combine CoffeeScript with jQuery and LocalStorage in order to create a simple contact list app.

 

Have you used CoffeeScript to simplify JavaScript? What parts of CoffeeScript do you prefer to Javascript? Let us know in the comments.

Featured image/thumbnail, coffee image via Shutterstock.

Share this post
Comments (no login required)
  • http://twitter.com/danklingjr Daniel E Kling Jr

    Interesting, never used this before.

  • shivabeach

    CSS1? And I am just learning this? Know anyplace that makes remedial CSS1 courses? :)

  • Mrbizle

    You can number lists!? I knew you could have an un-ordered list but this is just mindblowing… Its like some kind of ordered list… Whoda thunk it eh.

    This isnt a good use case. Im sure there is on but its not this!

  • Benjie

    Yes, apologies for the inconvenience, Disqus seem to be having issues again. We’re checking with their support team to get this resolved.