Tags

, ,


“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”

If your writing JavaScript in your web application, and the chances are these days you will be, then CoffeeScript is well worth a look – if your like me and you don’t particularly like writing JavaScript then bare with me you might learn some new tricks – CoffeeScript attempts to make your life easier when writing JavaScript and for the most part does a good job, it’s not all plain sailing as you might expect if you have worked with JavaScript much in the past.

Ok lets crack on, if you have Visual Studio handy make sure you have installed the Web Essentials Extension. This is a beauty of an add-on and has a nice little add-on for CoffeeScript included.

  1. Open up a new web solution either MVC app or a Web app
  2. Right click on your solution and then click Add in the next menu look for CoffeeScript, click this and we have a new CoffeeScript file added to your solution.
  3. On the left hand pane of the split is where you type your CoffeeScript and this is converted into JavaScript on the right hand side.
  4. Each time you save your changes the JavaScript file is updated for you – if you make any syntactical changes incorrectly then the preview tab on the right hand side will show you which line the error is on.

Some CoffeeScript basics are as follows:-

  • Semicolons are not required -> ;
  • Parenthesis are usually not required -> ()
  • Curly braces are usually not required -> {}
  • Commas are sometimes not required -> ,
  • Indent your code by tabbing for the start of a code block
  • Decrease indentation – end of a code block
  • The following screen shot shows you Visual Studio 2012 using the Web Essentials extension and I have added some CoffeeScript on the left and Web Essentials does the rest for me turning this into JavaScript.

  • To learn more about CoffeeScript check out the official website here.

Summary
CoffeeScript can be useful when your using something like KnockoutJS and you want to structure your code nicely using JavaScript classes and namespaces – I have been suing it recently and it has good points and bad points.

The good: – It allows you to structure your JavaScript easily and you can use namespaces as you would within C# classes. Less code is always good in my opinion and with CoffeeScript its easier to write less code to create your JavaScript files.

The bad: – Tabbing indents your code and this is how you create functions and loops and so on, miss one tab out and you can be left scratching your head but with some care this should be easily fixed.

Learn anything useful? – please let me know by leaving a comment after the beep.