SlideShare a Scribd company logo
1 of 74
Download to read offline
Why
 CoffeeScript
 Is
 Awesome*




@jocranford         *IMO
Tuesday, 8 May 12
How CoffeeScript works

                                                Include via
                                                  <script>
                                                              webpage.
            file.coffee   Compile   file.js
                                                                html


                                             




Tuesday, 8 May 12
Getting started was EASY




Tuesday, 8 May 12
Installation with Node Package Manager




Tuesday, 8 May 12
Compiling a Coffee Script File




Tuesday, 8 May 12
Compiling Multiple Coffee Script Files




Tuesday, 8 May 12
Web Workbench Visual Studio Plugin




Tuesday, 8 May 12
Autogeneration of JavaScript




Tuesday, 8 May 12
Errors in Output Window




Tuesday, 8 May 12
Basic Syntax



Tuesday, 8 May 12
Object Definition
 var myPresentation = {
    title: "CoffeeScript",
    when: {
      day: "8 May 2012",
      time: "6:30pm"
    }
 };




Tuesday, 8 May 12
Object Definition
 var myPresentation = {
    title: "CoffeeScript",
    when: {
      day: "8 May 2012",
      time: "6:30pm"
    }
 };




 myPresentation =
   subject: "CoffeeScript”
   when:
     day: "8 May 2012"
     time: "6:30pm"




Tuesday, 8 May 12
Object Definition
 var myPresentation = {
    title: "CoffeeScript",
    when: {
      day: "8 May 2012",
      time: "6:30pm"
    }
 };




 myPresentation =
   subject: "CoffeeScript”
   when:
     day: "8 May 2012"
     time: "6:30pm"




Tuesday, 8 May 12
Function Definition
  function startPresentation(subject) {
      alert("A presentation about " + subject + " is now
  starting!");
  }

  var startPresentation = function(subject) {
      alert("A presentation about " + subject + " is now
  starting!");
  };

  startPresentation("JavaScript");




Tuesday, 8 May 12
Function Definition
  function startPresentation(subject) {
      alert("A presentation about " + subject + " is now
  starting!");
  }

  var startPresentation = function(subject) {
      alert("A presentation about " + subject + " is now
  starting!");
  };

  startPresentation("JavaScript");




  startPresentation = (subject) ->
    alert "A presentation about " + subject + " is now
  starting!"

  startPresentation "CoffeeScript"


Tuesday, 8 May 12
Function Definition
  function startPresentation(subject) {
      alert("A presentation about " + subject + " is now
  starting!");
  }

  var startPresentation = function(subject) {
      alert("A presentation about " + subject + " is now
  starting!");
  };

  startPresentation("JavaScript");




  startPresentation = (subject) ->
    alert "A presentation about " + subject + " is now
  starting!"

  startPresentation "CoffeeScript"


Tuesday, 8 May 12
Operators


              CoffeeScript
   JavaScript
              is              ===
              isnt            !==
              not             !
              and             &&
              or              ||
              of              in




Tuesday, 8 May 12
Syntactic Sugar




Tuesday, 8 May 12
String Interpolation

    var description = "This is a talk about " +
    myPresentation.subject + " by " + myPresentation.presenter
    + ". It will start at " + myPresentation.startTime + " and
    finish by " + myPresentation.endTime;




Tuesday, 8 May 12
String Interpolation

    var description = "This is a talk about " +
    myPresentation.subject + " by " + myPresentation.presenter
    + ". It will start at " + myPresentation.startTime + " and
    finish by " + myPresentation.endTime;




    description = "This is a talk about
    #{myPresentation.subject} by #{myPresentation.presenter}.
    It will start at #{myPresentation.startTime} and finish
    by #{myPresentation.endTime}"




Tuesday, 8 May 12
String Interpolation

    var description = "This is a talk about " +
    myPresentation.subject + " by " + myPresentation.presenter
    + ". It will start at " + myPresentation.startTime + " and
    finish by " + myPresentation.endTime;




    description = "This is a talk about
    #{myPresentation.subject} by #{myPresentation.presenter}.
    It will start at #{myPresentation.startTime} and finish
    by #{myPresentation.endTime}"




Tuesday, 8 May 12
@ replaces this
   var Presentation = function(title, presenter) {

          this.getHeadline = function() {
              return title + " by " + presenter;
          };

          this.showHeadline = function() {
              alert(this.getHeadline());
          };

   };




Tuesday, 8 May 12
@ replaces this
   var Presentation = function(title, presenter) {

          this.getHeadline = function() {
              return title + " by " + presenter;
          };

          this.showHeadline = function() {
              alert(this.getHeadline());
          };

   };

   class Presentation

        constructor: (@title, @presenter) ->

        getHeadline: ->
          "#{@title} by #{@presenter}"

        showHeadline: ->
          alert(@getHeadline())

Tuesday, 8 May 12
@ replaces this
   var Presentation = function(title, presenter) {

          this.getHeadline = function() {
              return title + " by " + presenter;
          };

          this.showHeadline = function() {
              alert(this.getHeadline());
          };

   };

   class Presentation

        constructor: (@title, @presenter) ->

        getHeadline: ->
          "#{@title} by #{@presenter}"

        showHeadline: ->
          alert(@getHeadline())

Tuesday, 8 May 12
functions return the last value

       function add(x, y) {
           return x + y;
       }




Tuesday, 8 May 12
functions return the last value

       function add(x, y) {
           return x + y;
       }




       add = (x, y) ->
         x + y




Tuesday, 8 May 12
functions return the last value

       function add(x, y) {
           return x + y;
       }




       add = (x, y) ->
         x + y




Tuesday, 8 May 12
Conditionals return automatically
   var textColor;

   if (result === "failed") {
       textColor = "red";
   } else if (result === "not run") {
       textColor = "yellow";
   } else {
       textColor = "green";
   }




Tuesday, 8 May 12
Conditionals return automatically
   var textColor;

   if (result === "failed") {
       textColor = "red";
   } else if (result === "not run") {
       textColor = "yellow";
   } else {
       textColor = "green";
   }



   textColor =
     if result is "failed"
       "red"
     else if result is "not run"
       "yellow"
     else
       "green"



Tuesday, 8 May 12
Conditionals return automatically
   var textColor;

   if (result === "failed") {
       textColor = "red";
   } else if (result === "not run") {
       textColor = "yellow";
   } else {
       textColor = "green";
   }



   textColor =
     if result is "failed"
       "red"
     else if result is "not run"
       "yellow"
     else
       "green"



Tuesday, 8 May 12
Protection from Evil




Tuesday, 8 May 12
In JavaScript, variables are global by default
    var tonightsPresentations = [ "CoffeeScript", "i18n",
    "Rails Conf"];

    var whoopsie = function() {
        tonightsPresentations = [];
        return tonightsPresentations;
    }




Tuesday, 8 May 12
In CoffeeScript, they are automatically scoped
    var tonightsPresentations = [ "CoffeeScript", "i18n",
    "Rails Conf"];

    var whoopsie = function() {
        teamHugPresentationList = [];
        return teamHugPresentationList;
    }



    tonightsPresentations = [ "CoffeeScript", "i18n", "Rails
    Conf"]

    whoopsie = ->
    ! tonightsPresentations = []
    ! tonightsPresentations




Tuesday, 8 May 12
WTF ...




             0 == "" and 0 =="0" are both TRUE ...
                     but "" == "0" is NOT!

                      false == "0" is TRUE ...
                    but false == "false" is NOT!




Tuesday, 8 May 12
WTF ...

             0 == "" and 0 =="0" are both TRUE ...
                     but "" == "0" is NOT!

                      false == "0" is TRUE ...
                    but false == "false" is NOT!



                             is => ===
                            isnt => !==
                             == -> ===



Tuesday, 8 May 12
✗
                      With

                       ✗;
                       ✗
                Reserved Keywords

Tuesday, 8 May 12
Consistency




Tuesday, 8 May 12
Example 1
  var Presentation = function(title, presenter) {
      return {
          getHeadline: function() {
               return title + " by " + presenter;
          }
      }
  };

  var myPresentation = Presentation("CoffeeScript", "Jo
  Cranford");




Tuesday, 8 May 12
Example 2
    var Presentation = function(title, presenter) {

           this.getHeadline = function() {
               return title + " by " + presenter;
           };

    };

    var myPresentation = new Presentation("CoffeeScript", "Jo
    Cranford");




Tuesday, 8 May 12
Example 3
   var Presentation = function(title, presenter) {
       this.title = title;
       this.presenter = presenter;
   };

   Presentation.prototype.getHeadline = function() {
       return this.title + " by " + this.presenter;
   };

   var myPresentation = new Presentation("CoffeeScript", "Jo
   Cranford");




Tuesday, 8 May 12
CoffeeScript

      class Presentation

         constructor: (@title, @presenter) ->

         getHeadline: ->
           @title + " " + @presenter




Tuesday, 8 May 12
Less Code




Tuesday, 8 May 12
Average Lines Of Code
         40

                            1.8X

         30




         20




         10




          0

                    JavaScript
                                   CoffeeScript

Tuesday, 8 May 12
For Loop
   var i, weatherInCities;
   weatherInCities = [];


   for(i = 0; i < listOfCities.length; i++) {
   !           var city = listOfCities[i];
   !           weatherInCities.push(city.name + ":" + city.weather);
   }




Tuesday, 8 May 12
For Loop
   var i, weatherInCities;
   weatherInCities = [];


   for(i = 0; i < listOfCities.length; i++) {
   !           var city = listOfCities[i];
   !           weatherInCities.push(city.name + ":" + city.weather);
   }




 weatherInCities =
 (("#{city.name}: #{city.weather}") for city in listOfCities)




Tuesday, 8 May 12
For Loop
   var i, weatherInCities;
   weatherInCities = [];


   for(i = 0; i < listOfCities.length; i++) {
   !           var city = listOfCities[i];
   !           weatherInCities.push(city.name + ":" + city.weather);
   }




 weatherInCities =
 (("#{city.name}: #{city.weather}") for city in listOfCities)




Tuesday, 8 May 12
For “Own” Loop

 var objectToString = function (obj) {
 !      var key, val, _results;
 !      _results = [];

 !           for (key in obj) {
 !           !      if (!obj.hasOwnProperty(key)) continue;
 !           !      val = obj[key];
 !           !      if (val !== null) _results.push(key + ":" + val);
 !           }
 !           return _results.join(",");
 };




Tuesday, 8 May 12
For “Own” Loop

 var objectToString = function (obj) {
 !      var key, val, _results;
 !      _results = [];

 !           for (key in obj) {
 !           !      if (!obj.hasOwnProperty(key)) continue;
 !           !      val = obj[key];
 !           !      if (val !== null) _results.push(key + ":" + val);
 !           }
 !           return _results.join(",");
 };




 objectToString = (obj) ->
   !    ("#{key}:#{val}" for own key, val of obj when val isnt
 null).join(“,")



Tuesday, 8 May 12
For “Own” Loop

 var objectToString = function (obj) {
 !      var key, val, _results;
 !      _results = [];

 !           for (key in obj) {
 !           !      if (!obj.hasOwnProperty(key)) continue;
 !           !      val = obj[key];
 !           !      if (val !== null) _results.push(key + ":" + val);
 !           }
 !           return _results.join(",");
 };




 objectToString = (obj) ->
   !    ("#{key}:#{val}" for own key, val of obj when val isnt
 null).join(“,")



Tuesday, 8 May 12
Constructor - JavaScript

   var Region = function(states) {
   !      this.states = states;
   };

   Region.prototype.findStatesBeginningWith = function(letter) {
   !      var matchingStates = [];
          for (var i = 0;i < this.states.length; i++) {
   !      !      state = this.states[i];
   !      !      if (state.substr(0,1) === letter) {
   !      !      !      matchingStates.push(state)
   !      !      }
   !      }
   !      return matchingStates;
   };




Tuesday, 8 May 12
Constructor - CoffeeScript


  class Region


     constructor: (@states) ->


     findStatesBeginningWith: (letter) ->
         state for state in @states when state.substr(0,1) is letter




Tuesday, 8 May 12
Constructor - CoffeeScript


  class Region


     constructor: (@states) ->


     findStatesBeginningWith: (letter) ->
         state for state in @states when state.substr(0,1) is letter




Tuesday, 8 May 12
this and that
  var Clickable = function (baseElement) {
  !           var that = this;
  !           this.displayAlert = function() {
  !           !     alert("You just clicked me!");
  !           };
  !           $(baseElement).click(that.displayAlert);
  };




Tuesday, 8 May 12
this and that
  var Clickable = function (baseElement) {
  !           var that = this;
  !           this.displayAlert = function() {
  !           !     alert("You just clicked me!");
  !           };
  !           $(baseElement).click(that.displayAlert);
  };




Tuesday, 8 May 12
this and that
  var Clickable = function (baseElement) {
  !           var that = this;
  !           this.displayAlert = function() {
  !           !     alert("You just clicked me!");
  !           };
  !           $(baseElement).click(that.displayAlert);
  };



  class window.Clickable


       constructor: (@baseElement) ->
         $(@baseElement).click(@displayAlert)


       displayAlert: =>
         window.alert("You just clicked me!")


Tuesday, 8 May 12
this and that
  var Clickable = function (baseElement) {
  !           var that = this;
  !           this.displayAlert = function() {
  !           !     alert("You just clicked me!");
  !           };
  !           $(baseElement).click(that.displayAlert);
  };



  class window.Clickable


       constructor: (@baseElement) ->
         $(@baseElement).click(@displayAlert)


       displayAlert: =>
         window.alert("You just clicked me!")


Tuesday, 8 May 12
Pattern Matching – Reading an Object

   var london = {
      lat: 51.5171,
      lng: 0.1062
   };

   var lat = london.lat;
   var lng = london.lng;




Tuesday, 8 May 12
Pattern Matching – Reading an Object

   var london = {
      lat: 51.5171,
      lng: 0.1062
   };

   var lat = london.lat;
   var lng = london.lng;




   london =
     lat: 51.5171
     lng: 0.1062

   {lat,lng} = london




Tuesday, 8 May 12
Pattern Matching

   var london = {
      lat: 51.5171,
      lng: 0.1062
   };

   var lat = london.lat;
   var lng = london.lng;




   london =
     lat: 51.5171
     lng: 0.1062

   {lat,lng} = london




Tuesday, 8 May 12
Pattern Matching


      doSomethingWithPoint = ({lat,lng}) ->
          console.log(lat, lng);

      doSomethingWithPoint london




      createPoint = (lat, lng) ->
        { lat, lng }




Tuesday, 8 May 12
Existing libraries just work




Tuesday, 8 May 12
JQuery
    $(document).ready(function() {
        var tip = $("#js-tooltip");

           if (!tip.hasClass("hidden")) {
               tip.addClass("hidden");
           }
    });




Tuesday, 8 May 12
JQuery
    $(document).ready(function() {
        var tip = $("#js-tooltip");

           if (!tip.hasClass("hidden")) {
               tip.addClass("hidden");
           }
    });



    $(document).ready(->
      tip = $ "#coffee-tooltip"

        tip.addClass "hidden" unless tip.hasClass "hidden"
    )




Tuesday, 8 May 12
JQuery
    $(document).ready(function() {
        var tip = $("#js-tooltip");

           if (!tip.hasClass("hidden")) {
               tip.addClass("hidden");
           }
    });



    $(document).ready(->
      tip = $ "#coffee-tooltip"

        tip.addClass "hidden" unless tip.hasClass "hidden"
    )




Tuesday, 8 May 12
Easy to Test with Jasmine




Tuesday, 8 May 12
Jasmine Test
   describe("The Game Object", function() {

       it("should have a score of 0 if I knock down no
   skittles", function() {
           var game = new Game();
           game.roll(0);
           var score = game.score();
           expect(score).toBe(0);
       });
   });




Tuesday, 8 May 12
Jasmine Test
   describe("The Game Object", function() {

       it("should have a score of 0 if I knock down no
   skittles", function() {
           var game = new Game();
           game.roll(0);
           var score = game.score();
           expect(score).toBe(0);
       });
   });

   describe "The Game Object", ->

       it "should have a score of 0 if I knock down no skittles", -
   >
          game = new Game()
          game.roll(0)
          score = game.score()
          expect(score).toBe 0


Tuesday, 8 May 12
Clean, Efficient, Easy to Read
                              JavaScript




Tuesday, 8 May 12
class Presentation

          constructor: (@title, @presenter) ->

          getHeadline: ->
            "#{@title} #{@presenter}"




Tuesday, 8 May 12
(function() {
     var Presentation;

       Presentation = (function() {

          Presentation.name = 'Presentation';

          function Presentation(title, presenter) {
            this.title = title;
            this.presenter = presenter;
          }

          Presentation.prototype.getHeadline = function() {
             return this.title + " " + this.presenter;
          };

          return Presentation;

       })();


   }).call(this);


Tuesday, 8 May 12
(function() {
     var Presentation;

       Presentation = (function() {

          Presentation.name = 'Presentation';

          function Presentation(title, presenter) {
            this.title = title;
            this.presenter = presenter;
          }

          Presentation.prototype.getHeadline = function() {
             return this.title + " " + this.presenter;
          };

          return Presentation;

       })();


   }).call(this);


Tuesday, 8 May 12
Of course, it’s not perfect 




Tuesday, 8 May 12
It IS an additional step

                             Debugging

                    Shouldn't we just write good
                             JavaScript?

               Should we even be writing object
                     oriented JavaScript?



Tuesday, 8 May 12
References

           •    http://coffeescript.org/
           •    http://www.weave.de/wp-content/uploads/2012/01/The-Little-Book-on-
                Coffee-Script.pdf
           •    http://pragprog.com/magazines/2011-05/a-coffeescript-intervention
           •    http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/
           •    http://css.dzone.com/articles/source-maps-coffeescript
           •    http://www.quora.com/CoffeeScript/What-are-disadvantages-of-using-
                CoffeeScript
           •    http://www.readwriteweb.com/hack/2011/01/interview-coffeescript-jeremy-
                ashkenas.php
           •    http://rzrsharp.net/2011/06/27/what-does-coffeescripts-do-do.html
           •    http://stackoverflow.com/questions/643542/doesnt-javascript-support-
                closures-with-local-variables/643664#643664
           •    http://yannesposito.com/Scratch/en/blog/2011-01-03-Why-I-sadly-won-t-
                use-coffeescript/




Tuesday, 8 May 12

More Related Content

What's hot

Backbone js
Backbone jsBackbone js
Backbone jsrstankov
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptNone
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
History of jQuery
History of jQueryHistory of jQuery
History of jQueryjeresig
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineRaimonds Simanovskis
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmineRubyc Slides
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the ASTJarrod Overson
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1Vagmi Mudumbai
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessorAlessandro Nadalin
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 

What's hot (20)

Backbone js
Backbone jsBackbone js
Backbone js
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
History of jQuery
History of jQueryHistory of jQuery
History of jQuery
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 
HTML,CSS Next
HTML,CSS NextHTML,CSS Next
HTML,CSS Next
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
 
The state of your own hypertext preprocessor
The state of your own hypertext preprocessorThe state of your own hypertext preprocessor
The state of your own hypertext preprocessor
 
Coffee Script
Coffee ScriptCoffee Script
Coffee Script
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 

Similar to Why CoffeeScript Is Awesome

Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
Reason - introduction to language and its ecosystem | Łukasz Strączyński
Reason - introduction to language and its ecosystem | Łukasz StrączyńskiReason - introduction to language and its ecosystem | Łukasz Strączyński
Reason - introduction to language and its ecosystem | Łukasz StrączyńskiGrand Parade Poland
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 
CoffeeScript: JavaScript, but Better!
CoffeeScript: JavaScript, but Better! CoffeeScript: JavaScript, but Better!
CoffeeScript: JavaScript, but Better! Jack Franklin
 
Scala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаScala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаAlina Dolgikh
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love RubyBen Scheirman
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptForziatech
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Coffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesCoffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesBrandon Satrom
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jqueryciberglo
 
Parsing with Perl6 Grammars
Parsing with Perl6 GrammarsParsing with Perl6 Grammars
Parsing with Perl6 Grammarsabrummett
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
Planning JavaScript for Larger Teams - Draft & Handout version
Planning JavaScript for Larger Teams - Draft & Handout versionPlanning JavaScript for Larger Teams - Draft & Handout version
Planning JavaScript for Larger Teams - Draft & Handout versionChristian Heilmann
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 

Similar to Why CoffeeScript Is Awesome (20)

Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Reason - introduction to language and its ecosystem | Łukasz Strączyński
Reason - introduction to language and its ecosystem | Łukasz StrączyńskiReason - introduction to language and its ecosystem | Łukasz Strączyński
Reason - introduction to language and its ecosystem | Łukasz Strączyński
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
 
CoffeeScript: JavaScript, but Better!
CoffeeScript: JavaScript, but Better! CoffeeScript: JavaScript, but Better!
CoffeeScript: JavaScript, but Better!
 
Scala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаScala for the doubters. Максим Клыга
Scala for the doubters. Максим Клыга
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love Ruby
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Coffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesCoffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotes
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jquery
 
Practica n° 7
Practica n° 7Practica n° 7
Practica n° 7
 
Parsing with Perl6 Grammars
Parsing with Perl6 GrammarsParsing with Perl6 Grammars
Parsing with Perl6 Grammars
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
Planning JavaScript for Larger Teams - Draft & Handout version
Planning JavaScript for Larger Teams - Draft & Handout versionPlanning JavaScript for Larger Teams - Draft & Handout version
Planning JavaScript for Larger Teams - Draft & Handout version
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 

Recently uploaded

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Recently uploaded (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Why CoffeeScript Is Awesome

  • 1. Why CoffeeScript Is Awesome* @jocranford *IMO Tuesday, 8 May 12
  • 2. How CoffeeScript works Include via <script> webpage. file.coffee Compile file.js html   Tuesday, 8 May 12
  • 3. Getting started was EASY Tuesday, 8 May 12
  • 4. Installation with Node Package Manager Tuesday, 8 May 12
  • 5. Compiling a Coffee Script File Tuesday, 8 May 12
  • 6. Compiling Multiple Coffee Script Files Tuesday, 8 May 12
  • 7. Web Workbench Visual Studio Plugin Tuesday, 8 May 12
  • 9. Errors in Output Window Tuesday, 8 May 12
  • 11. Object Definition var myPresentation = { title: "CoffeeScript", when: { day: "8 May 2012", time: "6:30pm" } }; Tuesday, 8 May 12
  • 12. Object Definition var myPresentation = { title: "CoffeeScript", when: { day: "8 May 2012", time: "6:30pm" } }; myPresentation = subject: "CoffeeScript” when: day: "8 May 2012" time: "6:30pm" Tuesday, 8 May 12
  • 13. Object Definition var myPresentation = { title: "CoffeeScript", when: { day: "8 May 2012", time: "6:30pm" } }; myPresentation = subject: "CoffeeScript” when: day: "8 May 2012" time: "6:30pm" Tuesday, 8 May 12
  • 14. Function Definition function startPresentation(subject) { alert("A presentation about " + subject + " is now starting!"); } var startPresentation = function(subject) { alert("A presentation about " + subject + " is now starting!"); }; startPresentation("JavaScript"); Tuesday, 8 May 12
  • 15. Function Definition function startPresentation(subject) { alert("A presentation about " + subject + " is now starting!"); } var startPresentation = function(subject) { alert("A presentation about " + subject + " is now starting!"); }; startPresentation("JavaScript"); startPresentation = (subject) -> alert "A presentation about " + subject + " is now starting!" startPresentation "CoffeeScript" Tuesday, 8 May 12
  • 16. Function Definition function startPresentation(subject) { alert("A presentation about " + subject + " is now starting!"); } var startPresentation = function(subject) { alert("A presentation about " + subject + " is now starting!"); }; startPresentation("JavaScript"); startPresentation = (subject) -> alert "A presentation about " + subject + " is now starting!" startPresentation "CoffeeScript" Tuesday, 8 May 12
  • 17. Operators CoffeeScript JavaScript is === isnt !== not ! and && or || of in Tuesday, 8 May 12
  • 19. String Interpolation var description = "This is a talk about " + myPresentation.subject + " by " + myPresentation.presenter + ". It will start at " + myPresentation.startTime + " and finish by " + myPresentation.endTime; Tuesday, 8 May 12
  • 20. String Interpolation var description = "This is a talk about " + myPresentation.subject + " by " + myPresentation.presenter + ". It will start at " + myPresentation.startTime + " and finish by " + myPresentation.endTime; description = "This is a talk about #{myPresentation.subject} by #{myPresentation.presenter}. It will start at #{myPresentation.startTime} and finish by #{myPresentation.endTime}" Tuesday, 8 May 12
  • 21. String Interpolation var description = "This is a talk about " + myPresentation.subject + " by " + myPresentation.presenter + ". It will start at " + myPresentation.startTime + " and finish by " + myPresentation.endTime; description = "This is a talk about #{myPresentation.subject} by #{myPresentation.presenter}. It will start at #{myPresentation.startTime} and finish by #{myPresentation.endTime}" Tuesday, 8 May 12
  • 22. @ replaces this var Presentation = function(title, presenter) { this.getHeadline = function() { return title + " by " + presenter; }; this.showHeadline = function() { alert(this.getHeadline()); }; }; Tuesday, 8 May 12
  • 23. @ replaces this var Presentation = function(title, presenter) { this.getHeadline = function() { return title + " by " + presenter; }; this.showHeadline = function() { alert(this.getHeadline()); }; }; class Presentation constructor: (@title, @presenter) -> getHeadline: -> "#{@title} by #{@presenter}" showHeadline: -> alert(@getHeadline()) Tuesday, 8 May 12
  • 24. @ replaces this var Presentation = function(title, presenter) { this.getHeadline = function() { return title + " by " + presenter; }; this.showHeadline = function() { alert(this.getHeadline()); }; }; class Presentation constructor: (@title, @presenter) -> getHeadline: -> "#{@title} by #{@presenter}" showHeadline: -> alert(@getHeadline()) Tuesday, 8 May 12
  • 25. functions return the last value function add(x, y) { return x + y; } Tuesday, 8 May 12
  • 26. functions return the last value function add(x, y) { return x + y; } add = (x, y) -> x + y Tuesday, 8 May 12
  • 27. functions return the last value function add(x, y) { return x + y; } add = (x, y) -> x + y Tuesday, 8 May 12
  • 28. Conditionals return automatically var textColor; if (result === "failed") { textColor = "red"; } else if (result === "not run") { textColor = "yellow"; } else { textColor = "green"; } Tuesday, 8 May 12
  • 29. Conditionals return automatically var textColor; if (result === "failed") { textColor = "red"; } else if (result === "not run") { textColor = "yellow"; } else { textColor = "green"; } textColor = if result is "failed" "red" else if result is "not run" "yellow" else "green" Tuesday, 8 May 12
  • 30. Conditionals return automatically var textColor; if (result === "failed") { textColor = "red"; } else if (result === "not run") { textColor = "yellow"; } else { textColor = "green"; } textColor = if result is "failed" "red" else if result is "not run" "yellow" else "green" Tuesday, 8 May 12
  • 32. In JavaScript, variables are global by default var tonightsPresentations = [ "CoffeeScript", "i18n", "Rails Conf"]; var whoopsie = function() { tonightsPresentations = []; return tonightsPresentations; } Tuesday, 8 May 12
  • 33. In CoffeeScript, they are automatically scoped var tonightsPresentations = [ "CoffeeScript", "i18n", "Rails Conf"]; var whoopsie = function() { teamHugPresentationList = []; return teamHugPresentationList; } tonightsPresentations = [ "CoffeeScript", "i18n", "Rails Conf"] whoopsie = -> ! tonightsPresentations = [] ! tonightsPresentations Tuesday, 8 May 12
  • 34. WTF ... 0 == "" and 0 =="0" are both TRUE ... but "" == "0" is NOT! false == "0" is TRUE ... but false == "false" is NOT! Tuesday, 8 May 12
  • 35. WTF ... 0 == "" and 0 =="0" are both TRUE ... but "" == "0" is NOT! false == "0" is TRUE ... but false == "false" is NOT! is => === isnt => !== == -> === Tuesday, 8 May 12
  • 36. With ✗; ✗ Reserved Keywords Tuesday, 8 May 12
  • 38. Example 1 var Presentation = function(title, presenter) { return { getHeadline: function() { return title + " by " + presenter; } } }; var myPresentation = Presentation("CoffeeScript", "Jo Cranford"); Tuesday, 8 May 12
  • 39. Example 2 var Presentation = function(title, presenter) { this.getHeadline = function() { return title + " by " + presenter; }; }; var myPresentation = new Presentation("CoffeeScript", "Jo Cranford"); Tuesday, 8 May 12
  • 40. Example 3 var Presentation = function(title, presenter) { this.title = title; this.presenter = presenter; }; Presentation.prototype.getHeadline = function() { return this.title + " by " + this.presenter; }; var myPresentation = new Presentation("CoffeeScript", "Jo Cranford"); Tuesday, 8 May 12
  • 41. CoffeeScript class Presentation constructor: (@title, @presenter) -> getHeadline: -> @title + " " + @presenter Tuesday, 8 May 12
  • 43. Average Lines Of Code 40 1.8X 30 20 10 0 JavaScript CoffeeScript Tuesday, 8 May 12
  • 44. For Loop var i, weatherInCities; weatherInCities = []; for(i = 0; i < listOfCities.length; i++) { ! var city = listOfCities[i]; ! weatherInCities.push(city.name + ":" + city.weather); } Tuesday, 8 May 12
  • 45. For Loop var i, weatherInCities; weatherInCities = []; for(i = 0; i < listOfCities.length; i++) { ! var city = listOfCities[i]; ! weatherInCities.push(city.name + ":" + city.weather); } weatherInCities = (("#{city.name}: #{city.weather}") for city in listOfCities) Tuesday, 8 May 12
  • 46. For Loop var i, weatherInCities; weatherInCities = []; for(i = 0; i < listOfCities.length; i++) { ! var city = listOfCities[i]; ! weatherInCities.push(city.name + ":" + city.weather); } weatherInCities = (("#{city.name}: #{city.weather}") for city in listOfCities) Tuesday, 8 May 12
  • 47. For “Own” Loop var objectToString = function (obj) { ! var key, val, _results; ! _results = []; ! for (key in obj) { ! ! if (!obj.hasOwnProperty(key)) continue; ! ! val = obj[key]; ! ! if (val !== null) _results.push(key + ":" + val); ! } ! return _results.join(","); }; Tuesday, 8 May 12
  • 48. For “Own” Loop var objectToString = function (obj) { ! var key, val, _results; ! _results = []; ! for (key in obj) { ! ! if (!obj.hasOwnProperty(key)) continue; ! ! val = obj[key]; ! ! if (val !== null) _results.push(key + ":" + val); ! } ! return _results.join(","); }; objectToString = (obj) -> ! ("#{key}:#{val}" for own key, val of obj when val isnt null).join(“,") Tuesday, 8 May 12
  • 49. For “Own” Loop var objectToString = function (obj) { ! var key, val, _results; ! _results = []; ! for (key in obj) { ! ! if (!obj.hasOwnProperty(key)) continue; ! ! val = obj[key]; ! ! if (val !== null) _results.push(key + ":" + val); ! } ! return _results.join(","); }; objectToString = (obj) -> ! ("#{key}:#{val}" for own key, val of obj when val isnt null).join(“,") Tuesday, 8 May 12
  • 50. Constructor - JavaScript var Region = function(states) { ! this.states = states; }; Region.prototype.findStatesBeginningWith = function(letter) { ! var matchingStates = []; for (var i = 0;i < this.states.length; i++) { ! ! state = this.states[i]; ! ! if (state.substr(0,1) === letter) { ! ! ! matchingStates.push(state) ! ! } ! } ! return matchingStates; }; Tuesday, 8 May 12
  • 51. Constructor - CoffeeScript class Region constructor: (@states) -> findStatesBeginningWith: (letter) -> state for state in @states when state.substr(0,1) is letter Tuesday, 8 May 12
  • 52. Constructor - CoffeeScript class Region constructor: (@states) -> findStatesBeginningWith: (letter) -> state for state in @states when state.substr(0,1) is letter Tuesday, 8 May 12
  • 53. this and that var Clickable = function (baseElement) { ! var that = this; ! this.displayAlert = function() { ! ! alert("You just clicked me!"); ! }; ! $(baseElement).click(that.displayAlert); }; Tuesday, 8 May 12
  • 54. this and that var Clickable = function (baseElement) { ! var that = this; ! this.displayAlert = function() { ! ! alert("You just clicked me!"); ! }; ! $(baseElement).click(that.displayAlert); }; Tuesday, 8 May 12
  • 55. this and that var Clickable = function (baseElement) { ! var that = this; ! this.displayAlert = function() { ! ! alert("You just clicked me!"); ! }; ! $(baseElement).click(that.displayAlert); }; class window.Clickable constructor: (@baseElement) -> $(@baseElement).click(@displayAlert) displayAlert: => window.alert("You just clicked me!") Tuesday, 8 May 12
  • 56. this and that var Clickable = function (baseElement) { ! var that = this; ! this.displayAlert = function() { ! ! alert("You just clicked me!"); ! }; ! $(baseElement).click(that.displayAlert); }; class window.Clickable constructor: (@baseElement) -> $(@baseElement).click(@displayAlert) displayAlert: => window.alert("You just clicked me!") Tuesday, 8 May 12
  • 57. Pattern Matching – Reading an Object var london = { lat: 51.5171, lng: 0.1062 }; var lat = london.lat; var lng = london.lng; Tuesday, 8 May 12
  • 58. Pattern Matching – Reading an Object var london = { lat: 51.5171, lng: 0.1062 }; var lat = london.lat; var lng = london.lng; london = lat: 51.5171 lng: 0.1062 {lat,lng} = london Tuesday, 8 May 12
  • 59. Pattern Matching var london = { lat: 51.5171, lng: 0.1062 }; var lat = london.lat; var lng = london.lng; london = lat: 51.5171 lng: 0.1062 {lat,lng} = london Tuesday, 8 May 12
  • 60. Pattern Matching doSomethingWithPoint = ({lat,lng}) -> console.log(lat, lng); doSomethingWithPoint london createPoint = (lat, lng) -> { lat, lng } Tuesday, 8 May 12
  • 61. Existing libraries just work Tuesday, 8 May 12
  • 62. JQuery $(document).ready(function() { var tip = $("#js-tooltip"); if (!tip.hasClass("hidden")) { tip.addClass("hidden"); } }); Tuesday, 8 May 12
  • 63. JQuery $(document).ready(function() { var tip = $("#js-tooltip"); if (!tip.hasClass("hidden")) { tip.addClass("hidden"); } }); $(document).ready(-> tip = $ "#coffee-tooltip" tip.addClass "hidden" unless tip.hasClass "hidden" ) Tuesday, 8 May 12
  • 64. JQuery $(document).ready(function() { var tip = $("#js-tooltip"); if (!tip.hasClass("hidden")) { tip.addClass("hidden"); } }); $(document).ready(-> tip = $ "#coffee-tooltip" tip.addClass "hidden" unless tip.hasClass "hidden" ) Tuesday, 8 May 12
  • 65. Easy to Test with Jasmine Tuesday, 8 May 12
  • 66. Jasmine Test describe("The Game Object", function() { it("should have a score of 0 if I knock down no skittles", function() { var game = new Game(); game.roll(0); var score = game.score(); expect(score).toBe(0); }); }); Tuesday, 8 May 12
  • 67. Jasmine Test describe("The Game Object", function() { it("should have a score of 0 if I knock down no skittles", function() { var game = new Game(); game.roll(0); var score = game.score(); expect(score).toBe(0); }); }); describe "The Game Object", -> it "should have a score of 0 if I knock down no skittles", - > game = new Game() game.roll(0) score = game.score() expect(score).toBe 0 Tuesday, 8 May 12
  • 68. Clean, Efficient, Easy to Read JavaScript Tuesday, 8 May 12
  • 69. class Presentation constructor: (@title, @presenter) -> getHeadline: -> "#{@title} #{@presenter}" Tuesday, 8 May 12
  • 70. (function() { var Presentation; Presentation = (function() { Presentation.name = 'Presentation'; function Presentation(title, presenter) { this.title = title; this.presenter = presenter; } Presentation.prototype.getHeadline = function() { return this.title + " " + this.presenter; }; return Presentation; })(); }).call(this); Tuesday, 8 May 12
  • 71. (function() { var Presentation; Presentation = (function() { Presentation.name = 'Presentation'; function Presentation(title, presenter) { this.title = title; this.presenter = presenter; } Presentation.prototype.getHeadline = function() { return this.title + " " + this.presenter; }; return Presentation; })(); }).call(this); Tuesday, 8 May 12
  • 72. Of course, it’s not perfect  Tuesday, 8 May 12
  • 73. It IS an additional step Debugging Shouldn't we just write good JavaScript? Should we even be writing object oriented JavaScript? Tuesday, 8 May 12
  • 74. References • http://coffeescript.org/ • http://www.weave.de/wp-content/uploads/2012/01/The-Little-Book-on- Coffee-Script.pdf • http://pragprog.com/magazines/2011-05/a-coffeescript-intervention • http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/ • http://css.dzone.com/articles/source-maps-coffeescript • http://www.quora.com/CoffeeScript/What-are-disadvantages-of-using- CoffeeScript • http://www.readwriteweb.com/hack/2011/01/interview-coffeescript-jeremy- ashkenas.php • http://rzrsharp.net/2011/06/27/what-does-coffeescripts-do-do.html • http://stackoverflow.com/questions/643542/doesnt-javascript-support- closures-with-local-variables/643664#643664 • http://yannesposito.com/Scratch/en/blog/2011-01-03-Why-I-sadly-won-t- use-coffeescript/ Tuesday, 8 May 12