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

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
Thomas Fuchs
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
None
 
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
Jarod Ferguson
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
Rubyc Slides
 

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 (I think) CoffeeScript Is Awesome

Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
jhchabran
 
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
Paulo 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 Jasmine
Raimonds Simanovskis
 

Similar to Why (I think) 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

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Why (I think) 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