SlideShare ist ein Scribd-Unternehmen logo
1 von 74
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Kürzlich hochgeladen (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

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