Your SlideShare is downloading. ×
0
Why CoffeeScript Is Awesome*@jocranford         *IMOTuesday, 8 May 12
How CoffeeScript works                                                Include via                                         ...
Getting started was EASYTuesday, 8 May 12
Installation with Node Package ManagerTuesday, 8 May 12
Compiling a Coffee Script FileTuesday, 8 May 12
Compiling Multiple Coffee Script FilesTuesday, 8 May 12
Web Workbench Visual Studio PluginTuesday, 8 May 12
Autogeneration of JavaScriptTuesday, 8 May 12
Errors in Output WindowTuesday, 8 May 12
Basic SyntaxTuesday, 8 May 12
Object Definition var myPresentation = {    title: "CoffeeScript",    when: {      day: "8 May 2012",      time: "6:30pm"  ...
Object Definition var myPresentation = {    title: "CoffeeScript",    when: {      day: "8 May 2012",      time: "6:30pm"  ...
Object Definition var myPresentation = {    title: "CoffeeScript",    when: {      day: "8 May 2012",      time: "6:30pm"  ...
Function Definition  function startPresentation(subject) {      alert("A presentation about " + subject + " is now  startin...
Function Definition  function startPresentation(subject) {      alert("A presentation about " + subject + " is now  startin...
Function Definition  function startPresentation(subject) {      alert("A presentation about " + subject + " is now  startin...
Operators              CoffeeScript   JavaScript              is              ===              isnt            !==        ...
Syntactic SugarTuesday, 8 May 12
String Interpolation    var description = "This is a talk about " +    myPresentation.subject + " by " + myPresentation.pr...
String Interpolation    var description = "This is a talk about " +    myPresentation.subject + " by " + myPresentation.pr...
String Interpolation    var description = "This is a talk about " +    myPresentation.subject + " by " + myPresentation.pr...
@ replaces this   var Presentation = function(title, presenter) {          this.getHeadline = function() {              re...
@ replaces this   var Presentation = function(title, presenter) {          this.getHeadline = function() {              re...
@ replaces this   var Presentation = function(title, presenter) {          this.getHeadline = function() {              re...
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...
functions return the last value       function add(x, y) {           return x + y;       }       add = (x, y) ->         x...
Conditionals return automatically   var textColor;   if (result === "failed") {       textColor = "red";   } else if (resu...
Conditionals return automatically   var textColor;   if (result === "failed") {       textColor = "red";   } else if (resu...
Conditionals return automatically   var textColor;   if (result === "failed") {       textColor = "red";   } else if (resu...
Protection from EvilTuesday, 8 May 12
In JavaScript, variables are global by default    var tonightsPresentations = [ "CoffeeScript", "i18n",    "Rails Conf"]; ...
In CoffeeScript, they are automatically scoped    var tonightsPresentations = [ "CoffeeScript", "i18n",    "Rails Conf"]; ...
WTF ...             0 == "" and 0 =="0" are both TRUE ...                     but "" == "0" is NOT!                      f...
WTF ...             0 == "" and 0 =="0" are both TRUE ...                     but "" == "0" is NOT!                      f...
✗                      With                       ✗;                       ✗                Reserved KeywordsTuesday, 8 Ma...
ConsistencyTuesday, 8 May 12
Example 1  var Presentation = function(title, presenter) {      return {          getHeadline: function() {               ...
Example 2    var Presentation = function(title, presenter) {           this.getHeadline = function() {               retur...
Example 3   var Presentation = function(title, presenter) {       this.title = title;       this.presenter = presenter;   ...
CoffeeScript      class Presentation         constructor: (@title, @presenter) ->         getHeadline: ->           @title...
Less CodeTuesday, 8 May 12
Average Lines Of Code         40                            1.8X         30         20         10          0              ...
For Loop   var i, weatherInCities;   weatherInCities = [];   for(i = 0; i < listOfCities.length; i++) {   !           var ...
For Loop   var i, weatherInCities;   weatherInCities = [];   for(i = 0; i < listOfCities.length; i++) {   !           var ...
For Loop   var i, weatherInCities;   weatherInCities = [];   for(i = 0; i < listOfCities.length; i++) {   !           var ...
For “Own” Loop var objectToString = function (obj) { !      var key, val, _results; !      _results = []; !           for ...
For “Own” Loop var objectToString = function (obj) { !      var key, val, _results; !      _results = []; !           for ...
For “Own” Loop var objectToString = function (obj) { !      var key, val, _results; !      _results = []; !           for ...
Constructor - JavaScript   var Region = function(states) {   !      this.states = states;   };   Region.prototype.findStat...
Constructor - CoffeeScript  class Region     constructor: (@states) ->     findStatesBeginningWith: (letter) ->         st...
Constructor - CoffeeScript  class Region     constructor: (@states) ->     findStatesBeginningWith: (letter) ->         st...
this and that  var Clickable = function (baseElement) {  !           var that = this;  !           this.displayAlert = fun...
this and that  var Clickable = function (baseElement) {  !           var that = this;  !           this.displayAlert = fun...
this and that  var Clickable = function (baseElement) {  !           var that = this;  !           this.displayAlert = fun...
this and that  var Clickable = function (baseElement) {  !           var that = this;  !           this.displayAlert = fun...
Pattern Matching – Reading an Object   var london = {      lat: 51.5171,      lng: 0.1062   };   var lat = london.lat;   v...
Pattern Matching – Reading an Object   var london = {      lat: 51.5171,      lng: 0.1062   };   var lat = london.lat;   v...
Pattern Matching   var london = {      lat: 51.5171,      lng: 0.1062   };   var lat = london.lat;   var lng = london.lng;...
Pattern Matching      doSomethingWithPoint = ({lat,lng}) ->          console.log(lat, lng);      doSomethingWithPoint lond...
Existing libraries just workTuesday, 8 May 12
JQuery    $(document).ready(function() {        var tip = $("#js-tooltip");           if (!tip.hasClass("hidden")) {      ...
JQuery    $(document).ready(function() {        var tip = $("#js-tooltip");           if (!tip.hasClass("hidden")) {      ...
JQuery    $(document).ready(function() {        var tip = $("#js-tooltip");           if (!tip.hasClass("hidden")) {      ...
Easy to Test with JasmineTuesday, 8 May 12
Jasmine Test   describe("The Game Object", function() {       it("should have a score of 0 if I knock down no   skittles",...
Jasmine Test   describe("The Game Object", function() {       it("should have a score of 0 if I knock down no   skittles",...
Clean, Efficient, Easy to Read                              JavaScriptTuesday, 8 May 12
class Presentation          constructor: (@title, @presenter) ->          getHeadline: ->            "#{@title} #{@present...
(function() {     var Presentation;       Presentation = (function() {          Presentation.name = Presentation;         ...
(function() {     var Presentation;       Presentation = (function() {          Presentation.name = Presentation;         ...
Of course, it’s not perfect Tuesday, 8 May 12
It IS an additional step                             Debugging                    Shouldnt we just write good             ...
References           •    http://coffeescript.org/           •    http://www.weave.de/wp-content/uploads/2012/01/The-Littl...
Upcoming SlideShare
Loading in...5
×

Why (I think) CoffeeScript Is Awesome

3,408

Published on

Slides for a CoffeeScript presentation at Ruby on Rails Sydney user group on May 8.

2 Comments
3 Likes
Statistics
Notes
No Downloads
Views
Total Views
3,408
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
34
Comments
2
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "Why (I think) CoffeeScript Is Awesome"

  1. 1. Why CoffeeScript Is Awesome*@jocranford *IMOTuesday, 8 May 12
  2. 2. How CoffeeScript works Include via <script> webpage. file.coffee Compile file.js html  Tuesday, 8 May 12
  3. 3. Getting started was EASYTuesday, 8 May 12
  4. 4. Installation with Node Package ManagerTuesday, 8 May 12
  5. 5. Compiling a Coffee Script FileTuesday, 8 May 12
  6. 6. Compiling Multiple Coffee Script FilesTuesday, 8 May 12
  7. 7. Web Workbench Visual Studio PluginTuesday, 8 May 12
  8. 8. Autogeneration of JavaScriptTuesday, 8 May 12
  9. 9. Errors in Output WindowTuesday, 8 May 12
  10. 10. Basic SyntaxTuesday, 8 May 12
  11. 11. Object Definition var myPresentation = { title: "CoffeeScript", when: { day: "8 May 2012", time: "6:30pm" } };Tuesday, 8 May 12
  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. 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. 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. 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. 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. 17. Operators CoffeeScript JavaScript is === isnt !== not ! and && or || of inTuesday, 8 May 12
  18. 18. Syntactic SugarTuesday, 8 May 12
  19. 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. 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. 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. 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. 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. 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. 25. functions return the last value function add(x, y) { return x + y; }Tuesday, 8 May 12
  26. 26. functions return the last value function add(x, y) { return x + y; } add = (x, y) -> x + yTuesday, 8 May 12
  27. 27. functions return the last value function add(x, y) { return x + y; } add = (x, y) -> x + yTuesday, 8 May 12
  28. 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. 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. 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
  31. 31. Protection from EvilTuesday, 8 May 12
  32. 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. 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 = [] ! tonightsPresentationsTuesday, 8 May 12
  34. 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. 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. 36. ✗ With ✗; ✗ Reserved KeywordsTuesday, 8 May 12
  37. 37. ConsistencyTuesday, 8 May 12
  38. 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. 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. 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. 41. CoffeeScript class Presentation constructor: (@title, @presenter) -> getHeadline: -> @title + " " + @presenterTuesday, 8 May 12
  42. 42. Less CodeTuesday, 8 May 12
  43. 43. Average Lines Of Code 40 1.8X 30 20 10 0 JavaScript CoffeeScriptTuesday, 8 May 12
  44. 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. 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. 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. 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. 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. 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. 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. 51. Constructor - CoffeeScript class Region constructor: (@states) -> findStatesBeginningWith: (letter) -> state for state in @states when state.substr(0,1) is letterTuesday, 8 May 12
  52. 52. Constructor - CoffeeScript class Region constructor: (@states) -> findStatesBeginningWith: (letter) -> state for state in @states when state.substr(0,1) is letterTuesday, 8 May 12
  53. 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. 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. 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. 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. 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. 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} = londonTuesday, 8 May 12
  59. 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} = londonTuesday, 8 May 12
  60. 60. Pattern Matching doSomethingWithPoint = ({lat,lng}) -> console.log(lat, lng); doSomethingWithPoint london createPoint = (lat, lng) -> { lat, lng }Tuesday, 8 May 12
  61. 61. Existing libraries just workTuesday, 8 May 12
  62. 62. JQuery $(document).ready(function() { var tip = $("#js-tooltip"); if (!tip.hasClass("hidden")) { tip.addClass("hidden"); } });Tuesday, 8 May 12
  63. 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. 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. 65. Easy to Test with JasmineTuesday, 8 May 12
  66. 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. 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 0Tuesday, 8 May 12
  68. 68. Clean, Efficient, Easy to Read JavaScriptTuesday, 8 May 12
  69. 69. class Presentation constructor: (@title, @presenter) -> getHeadline: -> "#{@title} #{@presenter}"Tuesday, 8 May 12
  70. 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. 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. 72. Of course, it’s not perfect Tuesday, 8 May 12
  73. 73. It IS an additional step Debugging Shouldnt we just write good JavaScript? Should we even be writing object oriented JavaScript?Tuesday, 8 May 12
  74. 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
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×