Preface

I started my professional development career in 1999, when I first was paid a salary to be a developer. (I don’t count the few years before that when I was just having fun playing around on the Web.) In 1999 the Web was a scary place. HTML files were loaded down with font and table tags. CSS was just coming on the scene. JavaScript1 was only a few years old, and a battlefield of various implementations existed across the major browsers. Sure, you could write some JavaScript to do something in one browser, but would it work in another browser? Probably not. Because of that, JavaScript got a bad name in the early 2000s.

In the middle of the 2000s two important things happened that helped improve JavaScript in the eyes of web developers. The first was AJAX.2 AJAX enabled developers to make web pages more interactive, and faster, by making remote calls back to the server in the background without end users having to refresh their browsers.

The second was the popularity of JavaScript libraries, such as Prototype,3 that made writing cross-browser JavaScript much simpler. You could use AJAX to make your applications more responsive and easier to use and a library like Prototype to make sure it worked across major browsers.

In 2010, and certainly in 2011, the Web started evolving into “single page” applications. These applications were driven through the use of JavaScript frameworks, such as Backbone.js.4 These frameworks allowed the use of an MVC5 design pattern using JavaScript. Whole applications would be built in JavaScript and then downloaded and executed in the end user’s browser. This all made for incredibly responsive and rich client-side applications.

On the developer’s side, however, things weren’t all roses. Although the frameworks and tools made writing these sorts of applications easier, JavaScript itself proved to be the pain point. JavaScript is at times both an incredibly powerful language and an incredibly frustrating one. It is full of paradoxes and design traps that can quickly make your code unmanageable and bug ridden.

So what were developers to do? They want to build these great new applications, but the only universally accepted browser language is JavaScript. They could certainly write these applications in Flash,6 but that would require plug-ins, and it won’t work on some platforms, such as iOS7 devices.

I first discovered CoffeeScript8 in October 2010. CoffeeScript promised to help tame JavaScript and to expose the best parts of the quirky language that is JavaScript. It presented a cleaner syntax, like forgoing most punctuation in favor of significant whitespace and protection from those design traps that awaited JavaScript developers at every turn, such as poor scoping and misuse of the comparison operators. Best of all, it did all this while compiling to standard JavaScript that could then be executed in any browser or other JavaScript runtime environment.

When I first used CoffeeScript, the language was still very rough around the edges, even at version 0.9.4. I used it on a project for a client to try it out to see whether it was worth the little bit of hype I was hearing. Unfortunately, at the time two things caused me to push it aside. The first was that it was still not quite ready for prime time. There were too many bugs and missing features.

The second reason why I didn’t use CoffeeScript was because the app I was trying it out on wasn’t a very JavaScript-heavy application. I was mostly doing a few validation checks and an occasional bit of AJAX, which Ruby on Rails9 helped me do with very little, if any, JavaScript code.

So what made me come back to CoffeeScript? Some six months after I had tried out CoffeeScript for the first time, it was announced10 that Rails 3.1 would ship with CoffeeScript as the default JavaScript engine. Like most developers I was taken aback by this. I had tried CoffeeScript and didn’t think it was that great. What were they thinking?

Unlike a lot of my fellow developers, I took the time to have another look at CoffeeScript. Six months is a very long time in the development of any project. CoffeeScript had come a long, long way. I decided to try it again, this time on an application that had some pretty heavy JavaScript. Within a few days of using CoffeeScript again, I became not just a convert but an advocate of the language.

I’m not going to tell you exactly what it was that converted me, or try to tell you why I love it. I want you to form your own opinion. Over the course of this book I hope to both convert you and make you an advocate of this wonderful little language for reasons that are all your own. But I will give you a little sneak peak at what’s to come. Here’s a bit of CoffeeScript, from an actual application, followed by its equivalent JavaScript. Enjoy!

Example: (source: sneak_peak.coffee)


@updateAvatars = ->
  names = $('.avatar[data-name]').map -> $(this).data('name')
  Utils.findAvatar(name) for name in $.unique(names)


Example: (source: sneak_peak.js)


(function() {

  this.updateAvatars = function() {
    var name, names, _i, _len, _ref, _results;
    names = $('.avatar[data-name]').map(function() {
      return $(this).data('name'),
    });
    _ref = $.unique(names);
    _results = [];
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      name = _ref[_i];
      _results.push(Utils.findAvatar(name));
    }
    return _results;
  };

}).call(this);


What Is CoffeeScript?

CoffeeScript is a language that compiles down to JavaScript. Not very informative, I know, but it’s what it does. CoffeeScript was developed to closely resemble languages such as Ruby11 and Python.12 It was designed to help developers write their JavaScript more efficiently. By removing unnecessary punctuation like braces, semicolons, and so on, and by using significant whitespace to replace those characters, you can quickly focus on the code at hand—and not on making sure you have all your curly braces closed.

Chances are you would write the following JavaScript like this:

Example: (source: punctuation.js)


(function() {

  if (something === something_else) {
    console.log('do something'),
  } else {
    console.log('do something else'),
  }

}).call(this);


So why not write it like this:

Example: (source: punctuation.coffee)


if something is something_else
  console.log 'do something'
else
  console.log 'do something else'


CoffeeScript also gives you several shortcuts to write rather complicated sections of JavaScript with just a short code snippet. Take, for example, this code that lets you loop through the values in an array, without worrying about their indices:

Example: (source: array.coffee)


for name in array
  console.log name


Example: (source: array.js)


(function() {
  var name, _i, _len;

  for (_i = 0, _len = array.length; _i < _len; _i++) {
    name = array[_i];
    console.log(name);
  }

}).call(this);


In addition to the sugary sweet syntax improvements CoffeeScript gives you, it also helps you write better JavaScript code by doing things such as helping you scope your variables and classes appropriately, making sure you use the appropriate comparison operators, and much more, as you’ll see during the course of reading this book.

CoffeeScript, Ruby, and Python often get mentioned together in the same breath, and for good reason. CoffeeScript was directly modeled on the terseness and the simple syntax that these languages have to offer. Because of this, CoffeeScript has a much more modern “feel” than JavaScript does, which was modeled on languages such as Java13 and C++.14 Like JavaScript, CoffeeScript can be used in any programming environment. Whether you are writing your application using Ruby, Python, PHP,15 Java, or .Net,16 it doesn’t matter. The compiled JavaScript will work with them all.

Because CoffeeScript compiles down to JavaScript, you can still use any and all of the JavaScript libraries you currently use. You can use jQuery,17 Zepto,18 Backbone,19 Jasmine,20 and the like, and they’ll all just work. You don’t hear that too often when talking about new languages.

This all sounds great, I hear you saying, but what are the downsides of using CoffeeScript over just plain old JavaScript? This is a great question. The answer is, not much. First, although CoffeeScript is a really nice way to write your JavaScript, it does not let you do anything you couldn’t already do with JavaScript. I still can’t, for example, create a JavaScript version of Ruby’s famous method_missing.21 The biggest downside would have to be that it’s another language for you or the members of your team to learn. Fortunately, this is easily rectified. As you’ll see, CoffeeScript is incredibly easy to learn.

Finally, should CoffeeScript, for whatever reason, not be right for you or your project, you can take the generated JavaScript and work from there. So really, you have nothing to lose by giving CoffeeScript a try in your next project, or even in your current project (CoffeeScript and JavaScript play very well with each other).

Who Is This Book For?

This book is for intermediate- to advanced-level JavaScript developers. There are several reasons why I don’t think this book is good for those unfamiliar with JavaScript, or for those who only have a passing acquaintance.

First, this book is not going to teach you about JavaScript. This is a book about CoffeeScript. Along the way you are certainly going to learn a few bits and bobs about JavaScript (and CoffeeScript has a knack for making you learn more about JavaScript), but we are not going to start at the beginning of JavaScript and work our way up.

Example: What does this code do? (source: example.js)


(function() {
  var array, index, _i, _len;

  array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  for (_i = 0, _len = array.length; _i < _len; _i++) {
    index = array[_i];
    console.log(index);
  }

}).call(this);


If you don’t know what the preceding code example does, I recommend that you stop reading here. Don’t worry, I really want you to come back and keep reading. I just think that you will get the most out of this book if you already have a good understanding of JavaScript. I will be covering certain basic areas of JavaScript as we go along, usually to help illustrate a point or help you to better understand what CoffeeScript is doing. Despite covering certain areas of JavaScript for clarity, it really is important that you have a fundamental grasp of JavaScript before we continue. So please, go find a good book on JavaScript (there are plenty out there), read it, and then join me along our journey to become CoffeeScript gurus.

For those of you who are already JavaScript rock stars, let’s step up your game. This book is going to teach you how to write cleaner, more succinct, and better JavaScript using the sweet sugary goodness that is CoffeeScript.

How to Read This Book

I have to tried to present the material in this book to help you form building blocks to learning CoffeeScript. The chapters, in Part I, should be read in order because each chapter will build on the concepts that we have learned in previous chapters—so please, no jumping around.

As we go through each chapter, you’ll notice a few things at work.

First, whenever I introduce some outside library, idea, or concept, I include a footnote to a website where you can learn further information about that subject. Although I would love to be able to talk your ear off about things like Ruby, there is not enough space in this book to do that. So if I mention something and you want to find out more about it before continuing, go to the bookmarked site, quench your thirst for knowledge, and come back to the book.

Second, as we go through each chapter I will sometimes walk you through the wrong solution to a problem first. After you see the wrong way to do something, we can then examine it, understand it, and then work out the correct solution to the problem at hand. A great example of this is in Chapter 1, “Getting Started,” when we talk about the different ways to compile your CoffeeScript to JavaScript.

At some points in the book you will come across something like this:


Tip: Some helpful tip here.

These are little tips and tricks that I think might be of value to you.


Finally, throughout the book I will present you with two or three code blocks at a time. I will first give you the CoffeeScript example followed by the compiled (JavaScript) version of the same example. If there is any output from the example (and if I think it’s worth showing) I will include the output from the example, as well. Here’s what that looks like:

Example: (source: example.coffee)


array = [1..10]

for index in array
  console.log index


Example: (source: example.js)


(function() {
  var array, index, _i, _len;

  array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  for (_i = 0, _len = array.length; _i < _len; _i++) {
    index = array[_i];
    console.log(index);
  }

}).call(this);


Output: (source: example.coffee)


1
2
3
4
5
6
7
8
9
10


Sometimes there are errors that I want to show you. Here is an example:

Example: (source: oops.coffee)


array = [1..10]

oops! index in array
  console.log index


Output: (source: oops.coffee)


Error: In content/preface/oops.coffee, Parse error on line 3: Unexpected 'UNARY'
    at Object.parseError (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/parser.js:470:11)
    at Object.parse (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/parser.js:546:22)
    at /usr/local/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:40:22
    at Object.run (/usr/local/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:68:34)
    at /usr/local/lib/node_modules/coffee-script/lib/coffee-script/command.js:135:29
    at /usr/local/lib/node_modules/coffee-script/lib/coffee-script/command.js:110:18
    at [object Object].<anonymous> (fs.js:114:5)
    at [object Object].emit (events.js:64:17)
    at afterRead (fs.js:1081:12)
    at Object.wrapper [as oncomplete] (fs.js:252:17)


How This Book Is Organized

In an effort to help you get the most from this book, I have split it into two distinct parts.

Part I: Core CoffeeScript

The first part of this book is designed to cover the entire CoffeeScript language from top to bottom. By the end of this part of the book, you should be fully armed to attack any CoffeeScript project that comes your way, including those in the second part of this book.

Chapter 1, “Getting Started,” introduces the various ways CoffeeScript can be compiled and run. It also introduces the powerful coffee command-line utility and REPL that ships with CoffeeScript.

In Chapter 2, “The Basics,” we start to explore what makes CoffeeScript different from JavaScript. Talk of syntax, variables, scope, and more will lay a strong foundation for the rest of the book.

Chapter 3, “Control Structures,” focuses on an important part of any language, control structures such as if and else. You will also learn the differences between some operators in CoffeeScript and those in JavaScript.

Chapter 4, “Functions and Arguments,” covers the ins and outs of functions in CoffeeScript. We’ll talk about defining functions, calling functions, and a few extras such as default arguments and splats.

From arrays to objects, Chapter 5, “Collections and Iterations,” shows you how to use, manipulate, and iterate over collection objects in CoffeeScript.

Chapter 6, “Classes,” ends the first part of the book by covering classes in CoffeeScript. Define new classes, extend existing classes, override functions in super classes, and more.

Part II: CoffeeScript in Practice

The second part of this book focuses on using CoffeeScript in practical examples. Through learning about some of the ecosystem that surrounds CoffeeScript, as well as building a full application, by the end of Part II your CoffeeScript skills should be well honed.

Chapter 7, “Cake and Cakefiles,” covers the Cake tool that ships with CoffeeScript. You can use this little tool for creating build scripts, test scripts, and more. We’ll cover all that it has to offer.

Testing is a very important part of software development, and Chapter 8, “Testing with Jasmine,” gives a quick tour through one of the more popular CoffeeScript/JavaScript testing libraries, Jasmine. This chapter will exercise the popular pattern of test-driven development by writing tests first for a calculator class.

Chapter 9, “Intro to Node.js,” is a quick introduction to the event-driven server-side framework, Node.js. In this chapter we will use CoffeeScript to build a simple HTTP server that will automatically compile CoffeeScript files into JavaScript files as they are requested by the web browser.

In Chapter 10, “Example: Todo List Part 1 (Server-side),” we will be building the server-side part of a todo list application. Building on Chapter 9, we will build an API using the Express.js web framework and the Mongoose ORM for MongoDB.

In Chapter 11, “Example: Todo List Part 2 (Client-side w/ jQuery),” we will build a client for the todo list API we built in Chapter 10 using the popular jQuery libary.

Finally, in Chapter 12, “Example: Todo List Part 3 (Client-side w/ Backbone.js),” we will rebuild the client for the todo list application, this time forsaking jQuery in favor of the client-side framework, Backbone.js.

Installing CoffeeScript

I am not a big fan of having installation instructions in books, mostly because by the time the book hits the shelf, the installation instructions are out of date. However, people—and by people, I mean those who publish books—believe that there should be an installation section for books. So this is mine.

Installing CoffeeScript is pretty easy. The easiest way to install it is to go to http://www.coffeescript.org and look at the installation instructions there.

I believe the maintainers of projects like CoffeeScript and Node22 are the best people to keep the installation instructions up to date for their projects, and their websites are a great place to find those instructions.

At the time of writing, CoffeeScript was at version: 1.2.0. All examples in this book should work on that version.

How to Run the Examples

You will be able to find and download all the original source code for this book at https://github.com/markbates/Programming-In-CoffeeScript. As you’ll see, all the examples tell you which example file to look to. The example files will be in a folder relevant to their respective chapter.

Unless otherwise indicated, you should be able to run the examples in your terminal, like so:

> coffee example.coffee

So now that you know how to run the examples in this book, as soon as you have CoffeeScript installed, why don’t you meet me at Chapter 1 and we can get started? See you there.

Notes

1. http://en.wikipedia.org/wiki/JavaScript

2. http://en.wikipedia.org/wiki/Ajax_(programming)

3. http://www.prototypejs.org/

4. http://documentcloud.github.com/backbone/

5. http://en.wikipedia.org/wiki/Model–view–controller

6. http://www.adobe.com/

7. http://www.apple.com/ios/

8. http://www.coffeescript.org

9. http://www.rubyonrails.org

10. http://www.rubyinside.com/rails-3-1-adopts-coffeescript-jquery-sass-and-controversy-4669.html

11. http://en.wikipedia.org/wiki/Ruby_(programming_language)

12. http://en.wikipedia.org/wiki/Python_(programming_language)

13. http://en.wikipedia.org/wiki/Java_(programming_language)

14. http://en.wikipedia.org/wiki/C%2B%2B

15. http://en.wikipedia.org/wiki/Php

16. http://en.wikipedia.org/wiki/.NET_Framework

17. http://www.jquery.com

18. https://github.com/madrobby/zepto

19. http://documentcloud.github.com/backbone

20. http://pivotal.github.com/jasmine/

21. http://ruby-doc.org/docs/ProgrammingRuby/html/ref_c_object.html#Object.method_missing

22. http://nodejs.org

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.37.196