Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Understanding (JS === CoffeeScript)

Understanding (JS === CoffeeScript)

Coffeescript can be a really helpful tool, especially when you are working with a team of ruby developers, but there are a few gotchas that require really understanding Javascript to not shoot yourself in the foot.

Avatar for Alex Angelini

Alex Angelini

August 21, 2013
Tweet

Other Decks in Programming

Transcript

  1. Array.prototype.slice.call 1 var race, 2 __slice = [].slice; 3 4

    race = function() { 5 var runners, winner; 6 winner = arguments[0] 7 runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; 8 return print(winner, runners); 9 }; 1 race = (winner, runners...) -> 2 print winner, runners CoffeeScript Javascript Wednesday, August 21, 13
  2. void 0 CoffeeScript Javascript 1 a = undefined 1 var

    a; 2 3 a = void 0; Wednesday, August 21, 13
  3. _results.push CoffeeScript Javascript 1 expensiveOperation = -> 2 for stuff

    in allTheStuff 3 stuff.exec() 1 var expensiveOperation; 2 3 expensiveOperation = function() { 4 var stuff, _i, _len, _results; 5 _results = []; 6 for (_i = 0, _len = allTheStuff.length; _i < _len; _i++) { 7 stuff = allTheStuff[_i]; 8 _results.push(stuff.exec()); 9 } 10 return _results; 11 }; Wednesday, August 21, 13
  4. Triple Equal CoffeeScript Javascript 1 a == b 2 a

    is b 3 a != b 1 a === b; 2 3 a === b; 4 5 a !== b; Wednesday, August 21, 13
  5. hasOwnProperty CoffeeScript Javascript 1 for own key, val of obj

    2 console.log(key, val) 1 var key, val, 2 __hasProp = {}.hasOwnProperty; 3 4 for (key in obj) { 5 if (!__hasProp.call(obj, key)) continue; 6 val = obj[key]; 7 console.log(key, val); 8 } Wednesday, August 21, 13
  6. Existential Operator (?) CoffeeScript Javascript 1 a? 2 a =

    1 3 a? 4 a?() 1 var a; 2 3 typeof a !== "undefined" && a !== null; 4 5 a = 1; 6 7 a != null; 8 9 if (typeof a === "function") { 10 a(); 11 } Wednesday, August 21, 13
  7. (Safety?) Function CoffeeScript Javascript 1 a = 1 2 3

    task = (a) -> 4 a + 1 1 (function() { 2 3 var a, task; 4 5 a = 1; 6 7 task = function(a) { 8 return a + 1; 9 }; 10 11 })() Wednesday, August 21, 13
  8. Fat Arrow => CoffeeScript Javascript 1 class Car 2 constructor:

    (@speed) -> 3 @wheels = [0, 0, 10, 10] 4 5 move: -> 6 @wheels.map (wheel) => 7 wheel + @speed 8 return 1 var Car; 2 3 Car = (function() { 4 function Car(speed) { 5 this.speed = speed; 6 this.wheels = [0, 0, 10, 10]; 7 } 8 9 Car.prototype.move = function() { 10 var _this = this; 11 this.wheels.map(function(wheel) { 12 return wheel + _this.speed; 13 }); 14 }; 15 16 return Car; 17 18 })(); Wednesday, August 21, 13
  9. Function Calls CoffeeScript Javascript 1 a = -> 2 a

    3 a() 4 b(a) 5 b(a()) 1 var a; 2 3 a = function() {}; 4 5 a; 6 7 a(); 8 9 b(a); 10 11 b(a()); Wednesday, August 21, 13