SlideShare a Scribd company logo
1 of 101
COFFEESCRIPT
   A Rubyist’s Love Affair
Mark Bates
Distributed
Programming
    with
    Ruby
     Addison-Wesley
          2009


http://books.markbates.com
Programming
      in
 CoffeeScript
      Addison-Wesley
           2012


 http://books.markbates.com
A (BRIEF) HISTORY LESSON
“
I need to come up with a scripting language
for web browsers.


    I know! I'll make it cool and Lispy!      ”
               Dramatic Re-enactment (1995)
“   Yeah, So... Java is getting really popular.
    So we're going to need you to rewrite your
    language into something a bit more Java-
    esque and name it something like JavaScript.
 
    Yeah, and we're going to need it in a week.


    Thanks, that'd be great.    ”
                Dramatic Re-enactment (1995)
var MyApp.Models.Product = Backbone.Model.extend({

  isLiked: function() {
     var _ref;
     return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0);
  };

  like: function() {
     return new MyApp.Models.Like(this.get("like"));
  };

  image: function(size) {
     var img;
     if (size == null) {
       size = "full";
     }
     if (this.get("image") != null) {
       img = this.get("image")[size];
     }
     if (img == null) {
       img = "/images/fallback/product_" + size + "_default.png";
     }
     return img;
  };

});
FAST FORWARD
    About 15 Years
var MyApp.Models.Product = Backbone.Model.extend({

  isLiked: function() {
     var _ref;
     return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0);
  };

  like: function() {
     return new MyApp.Models.Like(this.get("like"));
  };

  image: function(size) {
     var img;
     if (size == null) {
       size = "full";
     }
     if (this.get("image") != null) {
       img = this.get("image")[size];
     }
     if (img == null) {
       img = "/images/fallback/product_" + size + "_default.png";
     }
     return img;
  };

});
class MyApp.Models.Product extends Backbone.Model

  isLiked: ->
    !@like()?.isNew()

  like: ->
    new MyApp.Models.Like(@get("like"))

  image: (size = "full") ->
    if @get("image")?
      img = @get("image")[size]
    unless img?
      img = "/images/fallback/product_#{size}_default.png"
    return img
WHAT IS COFFEESCRIPT?
What is CoffeeScript?
What is CoffeeScript?

“A little language that compiles into JavaScript.”
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript

Easier to read, write, maintain, refactor, etc...
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript

Easier to read, write, maintain, refactor, etc...

A Hybrid of Ruby and Python.
What is CoffeeScript?

“A little language that compiles into JavaScript.”

Easily integrates with your current JavaScript

Easier to read, write, maintain, refactor, etc...

A Hybrid of Ruby and Python.

Helpful.
What CoffeeScript Is Not?


Not Magic!

Limited by what JavaScript can already do
“
I’m happy writing JavaScript.

I don’t need to learn another language.   ”
FINE WITH ME
BUT...
.MODEL SMALL                           DISP:
                                               MOV BL,VAL1
.STACK 64                                      ADD BL,VAL2

.DATA                                          MOV   AH,00H
        VAL1       DB    01H                   MOV   AL,BL
        VAL2       DB    01H                   MOV   LP,CL
        LP         DB    00H                   MOV   CL,10
        V1         DB    00H                   DIV   CL
        V2         DB    00H                   MOV   CL,LP
        NL         DB    0DH,0AH,'$'
                                               MOV V1,AL
.CODE                                          MOV V2,AH

MAIN PROC                                      MOV   DL,V1
        MOV AX,@DATA                           ADD   DL,30H
        MOV DS,AX                              MOV   AH,02H
                                               INT   21H
        MOV    AH,01H
        INT    21H                             MOV   DL,V2
        MOV    CL,AL                           ADD   DL,30H
        SUB    CL,30H                          MOV   AH,02H
        SUB    CL,2                            INT   21H

        MOV    AH,02H                          MOV DL,VAL2
        MOV    DL,VAL1                         MOV VAL1,DL
        ADD    DL,30H                          MOV VAL2,BL
        INT    21H
                                               MOV AH,09H
        MOV AH,09H                             LEA DX,NL
        LEA DX,NL                              INT 21H
        INT 21H
                                               LOOP DISP
        MOV    AH,02H
        MOV    DL,VAL2                         MOV AH,4CH
        ADD    DL,30H                          INT 21H
        INT    21H
                                       MAIN ENDP
        MOV AH,09H                     END MAIN
        LEA DX,NL
        INT 21H
.MODEL SMALL                                      DISP:
                                       Assembly           MOV BL,VAL1
.STACK 64                                                 ADD BL,VAL2

.DATA                                                     MOV   AH,00H
        VAL1       DB    01H                              MOV   AL,BL
        VAL2       DB    01H                              MOV   LP,CL
        LP         DB    00H                              MOV   CL,10
        V1         DB    00H                              DIV   CL
        V2         DB    00H                              MOV   CL,LP
        NL         DB    0DH,0AH,'$'
                                                          MOV V1,AL
.CODE                                                     MOV V2,AH

MAIN PROC                                                 MOV   DL,V1
        MOV AX,@DATA                                      ADD   DL,30H
        MOV DS,AX                                         MOV   AH,02H
                                                          INT   21H
        MOV    AH,01H
        INT    21H                                        MOV   DL,V2
        MOV    CL,AL                                      ADD   DL,30H
        SUB    CL,30H                                     MOV   AH,02H
        SUB    CL,2                                       INT   21H

        MOV    AH,02H                                     MOV DL,VAL2
        MOV    DL,VAL1                                    MOV VAL1,DL
        ADD    DL,30H                                     MOV VAL2,BL
        INT    21H
                                                          MOV AH,09H
        MOV AH,09H                                        LEA DX,NL
        LEA DX,NL                                         INT 21H
        INT 21H
                                                          LOOP DISP
        MOV    AH,02H
        MOV    DL,VAL2                                    MOV AH,4CH
        ADD    DL,30H                                     INT 21H
        INT    21H
                                                  MAIN ENDP
        MOV AH,09H                                END MAIN
        LEA DX,NL
        INT 21H
#include <stdio.h>            C
int fibonacci()
{
  int n = 100;
  int a = 0;
  int b = 1;
  int sum;
  int i;

    for (i = 0; i < n; i++)
    {
      printf("%dn", a);
      sum = a + b;
      a = b;
      b = sum;
    }
    return 0;
}
public static void fibonacci() {    Java
  int n = 100;
  int a = 0;
  int b = 1;

    for (int i = 0; i < n; i++) {
      System.out.println(a);
      a = a + b;
      b = a - b;
    }
}
def fibonacci           Ruby
  a = 0
  b = 1

  100.times do
    printf("%dn", a)
    a, b = b, a + b
  end

end
“
I can write an app just as well in Java

as I can in Ruby, but damn it if Ruby


isn’t nicer to read and write!   ”
SAME GOES FOR
COFFEESCRIPT
SYNTAX
$(function() {                             $ ->
                                             success = (data) ->
  success = function(data) {                    if data.errors?
     if (data.errors != null) {                   alert "There was an error!"
       alert("There was an error!");            else
     } else {                                     $("#content").text(data.message)
       $("#content").text(data.message);
     }                                       $.get('/users', success, 'json')
  };

  $.get('/users', success, 'json');

});          JavaScript                                CoffeeScript
Syntax Rules

No semi-colons (ever!)

No curly braces*

No ‘function’ keyword

Relaxed parentheses

Whitespace significant formatting
Parentheses Rules
# Not required without arguments:
noArg1 = ->
  # do something

# Not required without arguments:
noArg2 = () ->
  # do something
                                # Required without arguments:
# Required with Arguments:      noArg1()
withArg = (arg) ->              noArg2()
  # do something
                               # Not required with
                               arguments:
                               withArg("bar")
                               withArg "bar"
Parentheses Rules
var noArg1, noArg2, withArg;

noArg1 = function() {};

noArg2 = function() {};

withArg = function(arg) {};

noArg1();

noArg2();

withArg("bar");

withArg("bar");
Parentheses Rules
# Bad:
$ "#some_id" .text()
# $("#some_id".text());

# Good:
$("#some_id").text()
# $("#some_id").text();
Whitespace
Whitespace
$(function() {
success = function(data) {
if (data.errors != null) {
alert("There was an error!");
} else {
$("#content").text(data.message);
}
};
$.get('/users', success, 'json');
});
Whitespace
$(function() {                      def fibonacci
success = function(data) {          a = 0
if (data.errors != null) {          b = 1
alert("There was an error!");       100.times do
} else {                            printf("%dn", a)
$("#content").text(data.message);   a, b = b, a + b
}                                   end
};                                  end
$.get('/users', success, 'json');
});
Whitespace
$(function() {                             def fibonacci
                                             a = 0
  success = function(data) {                 b = 1
     if (data.errors != null) {
       alert("There was an error!");         100.times do
     } else {                                  printf("%dn", a)
       $("#content").text(data.message);       a, b = b, a + b
     }                                       end
  };
                                           end
  $.get('/users', success, 'json');

});
Whitespace
$ ->
  success = (data) ->
     if data.errors?
       alert "There was an error!"
     else
       $("#content").text(data.message)

  $.get('/users', success, 'json')
Whitespace
$(function() {
  var success;
  success = function(data) {
     if (data.errors != null) {
       return alert("There was an error!");
     } else {
       return $("#content").text(data.message);
     }
  };
  return $.get('/users', success, 'json');
});
RUBYSCRIPT?
Conditionals
Conditionals
if true
  doSomething()

unless true
  doSomething()
Conditionals
if true                doSomething() if true
  doSomething()
                       doSomething() unless true
unless true
  doSomething()
Conditionals
if true                    doSomething() if true
  doSomething()
                           doSomething() unless true
unless true
  doSomething()
                   if true
                     doSomething()
                   else
                     doSomethingElse()
Objects/Hashes
someObject = {conf: "RailsConf", talk: "CoffeeScript"}

someObject =
  conf: "RailsConf"
  talk: "CoffeeScript"

someFunction(conf: "RailsConf", talk: "CoffeeScript")
Objects/Hashes
var someObject;

someObject = {
   conf: "RailsConf",
   talk: "CoffeeScript"
};

someObject = {
   conf: "RailsConf",
   talk: "CoffeeScript"
};

someFunction({
  conf: "RailsConf",
  talk: "CoffeeScript"
});
Ranges
a = [1..5]

b = [1...5]

c = [1..100]

d = [100..1]
Ranges
a = [1..5]     var a, b, c, d, _i, _j, _results, _results1;

               a = [1, 2, 3, 4, 5];
b = [1...5]
               b = [1, 2, 3, 4];
c = [1..100]
               c = (function() {
                 _results = [];
d = [100..1]     for (_i = 1; _i <= 100; _i++){ _results.push(_i); }
                 return _results;
               }).apply(this);

               d = (function() {
                 _results1 = [];
                 for (_j = 100; _j >= 1; _j--){ _results1.push(_j); }
                 return _results1;
               }).apply(this);
String Interpolation
name = "RailsConf 2012"

console.log "Hello #{name}"
# Hello RailsConf 2012

console.log 'Hello #{name}'
# Hello #{name}
String Interpolation
name = "RailsConf 2012"       var name;

console.log "Hello #{name}"   name = "RailsConf 2012";
# Hello RailsConf 2012
                              console.log("Hello " + name);
console.log 'Hello #{name}'
# Hello #{name}               console.log('Hello #{name}');
Heredocs
html = """
  <div class="comment" id="tweet-#{tweet.id_str}">
    <hr>
    <div class='tweet'>
      <span class="imgr"><img
src="#{tweet.profile_image_url}"></span>
      <span class="txtr">
         <h5><a href="http://twitter.com/#{tweet.from_user}"
target="_blank">@#{tweet.from_user}</a></h5>
         <p>#{tweet.text}</p>
         <p class="comment-posted-on">#{tweet.created_at}</p>
      </span>
    </div>
  </div>
"""
Heredocs
var html;

html = "<div class="comment" id="tweet-" + tweet.id_str
+ "">n <hr>n <div class='tweet'>n      <span class=
"imgr"><img src="" + tweet.profile_image_url + ""></
span>n    <span class="txtr">n      <h5><a href=
"http://twitter.com/" + tweet.from_user + "" target=
"_blank">@" + tweet.from_user + "</a></h5>n       <p>" +
tweet.text + "</p>n      <p class="comment-posted-on">"
+ tweet.created_at + "</p>n    </span>n </div>n</div>";
Functions
p = (name) ->
  console.log "Hello #{name}"

p('RailsConf 2012')
Functions
var p;

p = function(name) {
   return console.log("Hello " + name);
};

p('RailsConf 2012');
Functions
p = (name)->
  console.log "Hello #{name}"

p('RailsConf 2012')
Functions
p = (name)->
  console.log "Hello #{name}"     CoffeeScript
p('RailsConf 2012')
Functions
p = (name)->
  console.log "Hello #{name}"     CoffeeScript
p('RailsConf 2012')




p = ->(name) {
  puts "Hello #{name}"
}
                                  Ruby 1.9
p.call('RailsConf 2012')
Default Arguments
createElement = (name, attributes = {}) ->
  obj = document.createElement name
  for key, val of attributes
    obj.setAttribute key, val
  obj
Default Arguments
var createElement;

createElement = function(name, attributes) {
   var key, obj, val;
   if (attributes == null) {
     attributes = {};
   }
   obj = document.createElement(name);
   for (key in attributes) {
     val = attributes[key];
     obj.setAttribute(key, val);
   }
   return obj;
};
Splats*
splatter = (first, second, others...) ->
  console.log "First: #{first}"
  console.log "Second: #{second}"
  console.log "Others: #{others.join(', ')}"

splatter [1..5]...
Splats*
var splatter,
  __slice = [].slice;

splatter = function() {
   var first, others, second;
   first = arguments[0], second = arguments[1], others = 3
<= arguments.length ? __slice.call(arguments, 2) : [];
   console.log("First: " + first);
   console.log("Second: " + second);
   return console.log("Others: " + (others.join(', ')));
};

splatter.apply(null, [1, 2, 3, 4, 5]);
Loops & Comprehensions
for someName in someArray
  console.log someName

for key, value of someObject
  console.log "#{key}: #{value}"
Loops & Comprehensions
var key, someName, value, _i, _len;

for (_i = 0, _len = someArray.length; _i < _len; _i++) {
  someName = someArray[_i];
  console.log(someName);
}

for (key in someObject) {
  value = someObject[key];
  console.log("" + key + ": " + value);
}
Loops & Comprehensions
numbers = [1..5]

console.log number for number in numbers
Loops & Comprehensions
var number, numbers, _i, _len;

numbers = [1, 2, 3, 4, 5];

for (_i = 0, _len = numbers.length; _i < _len; _i++) {
  number = numbers[_i];
  console.log(number);
}
Loops & Comprehensions
numbers = [1..5]

console.log number for number in numbers when number <= 3
Loops & Comprehensions
var number, numbers, _i, _len;

numbers = [1, 2, 3, 4, 5];

for (_i = 0, _len = numbers.length; _i < _len; _i++) {
  number = numbers[_i];
  if (number <= 3) {
    console.log(number);
  }
}
Loops & Comprehensions
numbers = [1, 2, 3, 4, 5]

low_numbers = (number * 2 for number in numbers when number <= 3)

console.log low_numbers # [ 2, 4, 6 ]
Loops & Comprehensions
var low_numbers, number, numbers;

numbers = [1, 2, 3, 4, 5];

low_numbers = (function() {
  var _i, _len, _results;
  _results = [];
  for (_i = 0, _len = numbers.length; _i < _len; _i++) {
    number = numbers[_i];
    if (number <= 3) {
      _results.push(number * 2);
    }
  }
  return _results;
})();

console.log(low_numbers);
Classes
class Employee

emp = new Employee()
emp.firstName = "Mark"
Classes
var Employee, emp;

Employee = (function() {

  Employee.name = 'Employee';

  function Employee() {}

  return Employee;

})();

emp = new Employee();

emp.firstName = "Mark";
Classes
class Employee

  constructor: (@options = {}) ->

  salary: ->
    @options.salary ?= "$250,000"

emp = new Employee()
console.log emp.salary() # "$250,000"

emp = new Employee(salary: "$100,000")
console.log emp.salary() # "$100,000"
Classes
var Employee, emp;

Employee = (function() {

  Employee.name = 'Employee';

  function Employee(options) {
    this.options = options != null ? options : {};
  }

  Employee.prototype.salary = function() {
     var _base, _ref;
     return (_ref = (_base = this.options).salary) != null ? _ref : _base.salary = "$250,000";
  };

  return Employee;

})();

emp = new Employee();

console.log(emp.salary());

emp = new Employee({
  salary: "$100,000"
});

console.log(emp.salary());
Extending Classes
class Manager extends Employee

  constructor: ->
    super
    @options.salary ?= "$500,000"

manager = new Manager()
console.log manager.salary() # "$500,000"
Extending Classes
var Manager, manager,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key]
= parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype;
child.prototype = new ctor; child.__super__ = parent.prototype; return child; };

Manager = (function(_super) {

  __extends(Manager, _super);

  Manager.name = 'Manager';

  function Manager() {
    var _base;
    Manager.__super__.constructor.apply(this, arguments);
    if ((_base = this.options).salary == null) {
      _base.salary = "$500,000";
    }
  }

  return Manager;

})(Employee);

manager = new Manager();

console.log(manager.salary());
Extending Classes
class Manager extends Employee

  constructor: ->
    super
    @options.salary ?= "$500,000"

  salary: ->
    "#{super} + $10k"

manager = new Manager()
console.log manager.salary() # "$500,000 + $10k"
Extending Classes
var Manager, manager,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ =
parent.prototype; return child; };

Manager = (function(_super) {

  __extends(Manager, _super);

  Manager.name = 'Manager';

  function Manager() {
    var _base;
    Manager.__super__.constructor.apply(this, arguments);
    if ((_base = this.options).salary == null) {
      _base.salary = "$500,000";
    }
  }

  Manager.prototype.salary = function() {
     return "" + Manager.__super__.salary.apply(this, arguments) + " + $10k";
  };

  return Manager;

})(Employee);

manager = new Manager();

console.log(manager.salary());
Bound Functions
class User

  constructor: (@name) ->

  sayHi: ->
    console.log "Hello #{@name}"

bob = new User('bob')
mary = new User('mary')

log = (callback)->
  console.log "about to execute callback..."
  callback()
  console.log "...executed callback"

log(bob.sayHi)
log(mary.sayHi)
Bound Functions
about to execute callback...
Hello undefined
...executed callback
about to execute callback...
Hello undefined
...executed callback
Bound Functions
class User

  constructor: (@name) ->

  sayHi: ->
    console.log "Hello #{@name}"

bob = new User('bob')
mary = new User('mary')

log = (callback)->
  console.log "about to execute callback..."
  callback()
  console.log "...executed callback"

log(bob.sayHi)
log(mary.sayHi)
Bound Functions
class User

  constructor: (@name) ->

  sayHi: ->
    console.log "Hello #{@name}"

bob = new User('bob')
mary = new User('mary')

log = (callback)->
  console.log "about to execute callback..."
  callback()
  console.log "...executed callback"

log(bob.sayHi)
log(mary.sayHi)
Bound Functions
class User

  constructor: (@name) ->

  sayHi: =>
    console.log "Hello #{@name}"

bob = new User('bob')
mary = new User('mary')

log = (callback)->
  console.log "about to execute callback..."
  callback()
  console.log "...executed callback"

log(bob.sayHi)
log(mary.sayHi)
Bound Functions
about to execute callback...
Hello bob
...executed callback
about to execute callback...
Hello mary
...executed callback
Bound Functions
class User

  constructor: (@name) ->

  sayHi: =>
    console.log "Hello #{@name}"
Bound Functions
var User,
  __bind = function(fn, me){ return function(){ return fn.apply(me,
arguments); }; };

User = (function() {

  User.name = 'User';

  function User(name) {
    this.name = name;
    this.sayHi = __bind(this.sayHi, this);
  }

  User.prototype.sayHi = function() {
     return console.log("Hello " + this.name);
  };

  return User;

})();
FINALLY
One of my favorite features
Existential Operator
if foo?
  console.log "foo"

console.log "foo" if foo?
Existential Operator
if (typeof foo !== "undefined" && foo !== null) {
  console.log("foo");
}

if (typeof foo !== "undefined" && foo !== null) {
  console.log("foo");
}
WAIT! IT GETS BETTER!
Existential Operator
console?.log "foo"
Existential Operator
console?.log "foo"




if (typeof console !== "undefined" && console !== null) {
  console.log("foo");
}
Existential Operator
if currentUser?.firstName?
  console.log currentUser.firstName
Existential Operator
if currentUser?.firstName?
  console.log currentUser.firstName




if ((typeof currentUser !== "undefined" && currentUser !==
null ? currentUser.firstName : void 0) != null) {
  console.log(currentUser.firstName);
}
What Didn’t I Cover?
Scoping

Security

Strict Mode

Fixes common ‘mistakes’

Operators

The `do` keyword

Plenty more!
Thank You
Thank You
myName = "Mark Bates"

you.should buyBook("Programming in CoffeeScript")
 .at("http://books.markbates.com")

you.should followMe(@markbates)

More Related Content

More from Mark

Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web AppsMark
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js FundamentalsMark
 
Go(lang) for the Rubyist
Go(lang) for the RubyistGo(lang) for the Rubyist
Go(lang) for the RubyistMark
 
Mangling Ruby with TracePoint
Mangling Ruby with TracePointMangling Ruby with TracePoint
Mangling Ruby with TracePointMark
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsMark
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTestMark
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTestMark
 
GET /better
GET /betterGET /better
GET /betterMark
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptMark
 
Testing Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptTesting Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptMark
 
Building an API in Rails without Realizing It
Building an API in Rails without Realizing ItBuilding an API in Rails without Realizing It
Building an API in Rails without Realizing ItMark
 
5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(Mark
 
RubyMotion
RubyMotionRubyMotion
RubyMotionMark
 
Testing JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiTesting JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiMark
 
Testing Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineTesting Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineMark
 
DRb and Rinda
DRb and RindaDRb and Rinda
DRb and RindaMark
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Mark
 

More from Mark (18)

Building Go Web Apps
Building Go Web AppsBuilding Go Web Apps
Building Go Web Apps
 
Angular.js Fundamentals
Angular.js FundamentalsAngular.js Fundamentals
Angular.js Fundamentals
 
Go(lang) for the Rubyist
Go(lang) for the RubyistGo(lang) for the Rubyist
Go(lang) for the Rubyist
 
Mangling Ruby with TracePoint
Mangling Ruby with TracePointMangling Ruby with TracePoint
Mangling Ruby with TracePoint
 
AngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.jsAngularJS vs. Ember.js vs. Backbone.js
AngularJS vs. Ember.js vs. Backbone.js
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTest
 
A Big Look at MiniTest
A Big Look at MiniTestA Big Look at MiniTest
A Big Look at MiniTest
 
GET /better
GET /betterGET /better
GET /better
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Testing Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScriptTesting Your JavaScript & CoffeeScript
Testing Your JavaScript & CoffeeScript
 
Building an API in Rails without Realizing It
Building an API in Rails without Realizing ItBuilding an API in Rails without Realizing It
Building an API in Rails without Realizing It
 
5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(5 Favorite Gems (Lightning Talk(
5 Favorite Gems (Lightning Talk(
 
RubyMotion
RubyMotionRubyMotion
RubyMotion
 
Testing JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiTesting JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and Chai
 
Testing Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineTesting Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with Jasmine
 
DRb and Rinda
DRb and RindaDRb and Rinda
DRb and Rinda
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010Distributed Programming with Ruby/Rubyconf 2010
Distributed Programming with Ruby/Rubyconf 2010
 

Recently uploaded

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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"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
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
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
 
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
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
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
 

Recently uploaded (20)

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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"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
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
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
 
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
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
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
 

CoffeeScript: A Brief History and Introduction

  • 1. COFFEESCRIPT A Rubyist’s Love Affair
  • 3. Distributed Programming with Ruby Addison-Wesley 2009 http://books.markbates.com
  • 4. Programming in CoffeeScript Addison-Wesley 2012 http://books.markbates.com
  • 6.
  • 7. “ I need to come up with a scripting language for web browsers. I know! I'll make it cool and Lispy! ” Dramatic Re-enactment (1995)
  • 8.
  • 9. Yeah, So... Java is getting really popular. So we're going to need you to rewrite your language into something a bit more Java- esque and name it something like JavaScript.   Yeah, and we're going to need it in a week. Thanks, that'd be great. ” Dramatic Re-enactment (1995)
  • 10. var MyApp.Models.Product = Backbone.Model.extend({ isLiked: function() { var _ref; return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0); }; like: function() { return new MyApp.Models.Like(this.get("like")); }; image: function(size) { var img; if (size == null) { size = "full"; } if (this.get("image") != null) { img = this.get("image")[size]; } if (img == null) { img = "/images/fallback/product_" + size + "_default.png"; } return img; }; });
  • 11. FAST FORWARD About 15 Years
  • 12.
  • 13. var MyApp.Models.Product = Backbone.Model.extend({ isLiked: function() { var _ref; return ! ((_ref = this.like()) != null ? _ref.isNew() : void 0); }; like: function() { return new MyApp.Models.Like(this.get("like")); }; image: function(size) { var img; if (size == null) { size = "full"; } if (this.get("image") != null) { img = this.get("image")[size]; } if (img == null) { img = "/images/fallback/product_" + size + "_default.png"; } return img; }; });
  • 14. class MyApp.Models.Product extends Backbone.Model isLiked: -> !@like()?.isNew() like: -> new MyApp.Models.Like(@get("like")) image: (size = "full") -> if @get("image")? img = @get("image")[size] unless img? img = "/images/fallback/product_#{size}_default.png" return img
  • 17. What is CoffeeScript? “A little language that compiles into JavaScript.”
  • 18. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript
  • 19. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript Easier to read, write, maintain, refactor, etc...
  • 20. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript Easier to read, write, maintain, refactor, etc... A Hybrid of Ruby and Python.
  • 21. What is CoffeeScript? “A little language that compiles into JavaScript.” Easily integrates with your current JavaScript Easier to read, write, maintain, refactor, etc... A Hybrid of Ruby and Python. Helpful.
  • 22. What CoffeeScript Is Not? Not Magic! Limited by what JavaScript can already do
  • 23. “ I’m happy writing JavaScript. I don’t need to learn another language. ”
  • 26. .MODEL SMALL DISP: MOV BL,VAL1 .STACK 64 ADD BL,VAL2 .DATA MOV AH,00H VAL1 DB 01H MOV AL,BL VAL2 DB 01H MOV LP,CL LP DB 00H MOV CL,10 V1 DB 00H DIV CL V2 DB 00H MOV CL,LP NL DB 0DH,0AH,'$' MOV V1,AL .CODE MOV V2,AH MAIN PROC MOV DL,V1 MOV AX,@DATA ADD DL,30H MOV DS,AX MOV AH,02H INT 21H MOV AH,01H INT 21H MOV DL,V2 MOV CL,AL ADD DL,30H SUB CL,30H MOV AH,02H SUB CL,2 INT 21H MOV AH,02H MOV DL,VAL2 MOV DL,VAL1 MOV VAL1,DL ADD DL,30H MOV VAL2,BL INT 21H MOV AH,09H MOV AH,09H LEA DX,NL LEA DX,NL INT 21H INT 21H LOOP DISP MOV AH,02H MOV DL,VAL2 MOV AH,4CH ADD DL,30H INT 21H INT 21H MAIN ENDP MOV AH,09H END MAIN LEA DX,NL INT 21H
  • 27. .MODEL SMALL DISP: Assembly MOV BL,VAL1 .STACK 64 ADD BL,VAL2 .DATA MOV AH,00H VAL1 DB 01H MOV AL,BL VAL2 DB 01H MOV LP,CL LP DB 00H MOV CL,10 V1 DB 00H DIV CL V2 DB 00H MOV CL,LP NL DB 0DH,0AH,'$' MOV V1,AL .CODE MOV V2,AH MAIN PROC MOV DL,V1 MOV AX,@DATA ADD DL,30H MOV DS,AX MOV AH,02H INT 21H MOV AH,01H INT 21H MOV DL,V2 MOV CL,AL ADD DL,30H SUB CL,30H MOV AH,02H SUB CL,2 INT 21H MOV AH,02H MOV DL,VAL2 MOV DL,VAL1 MOV VAL1,DL ADD DL,30H MOV VAL2,BL INT 21H MOV AH,09H MOV AH,09H LEA DX,NL LEA DX,NL INT 21H INT 21H LOOP DISP MOV AH,02H MOV DL,VAL2 MOV AH,4CH ADD DL,30H INT 21H INT 21H MAIN ENDP MOV AH,09H END MAIN LEA DX,NL INT 21H
  • 28. #include <stdio.h> C int fibonacci() { int n = 100; int a = 0; int b = 1; int sum; int i; for (i = 0; i < n; i++) { printf("%dn", a); sum = a + b; a = b; b = sum; } return 0; }
  • 29. public static void fibonacci() { Java int n = 100; int a = 0; int b = 1; for (int i = 0; i < n; i++) { System.out.println(a); a = a + b; b = a - b; } }
  • 30. def fibonacci Ruby a = 0 b = 1 100.times do printf("%dn", a) a, b = b, a + b end end
  • 31. “ I can write an app just as well in Java as I can in Ruby, but damn it if Ruby isn’t nicer to read and write! ”
  • 34. $(function() { $ -> success = (data) -> success = function(data) { if data.errors? if (data.errors != null) { alert "There was an error!" alert("There was an error!"); else } else { $("#content").text(data.message) $("#content").text(data.message); } $.get('/users', success, 'json') }; $.get('/users', success, 'json'); }); JavaScript CoffeeScript
  • 35. Syntax Rules No semi-colons (ever!) No curly braces* No ‘function’ keyword Relaxed parentheses Whitespace significant formatting
  • 36. Parentheses Rules # Not required without arguments: noArg1 = -> # do something # Not required without arguments: noArg2 = () -> # do something # Required without arguments: # Required with Arguments: noArg1() withArg = (arg) -> noArg2() # do something # Not required with arguments: withArg("bar") withArg "bar"
  • 37. Parentheses Rules var noArg1, noArg2, withArg; noArg1 = function() {}; noArg2 = function() {}; withArg = function(arg) {}; noArg1(); noArg2(); withArg("bar"); withArg("bar");
  • 38. Parentheses Rules # Bad: $ "#some_id" .text() # $("#some_id".text()); # Good: $("#some_id").text() # $("#some_id").text();
  • 40. Whitespace $(function() { success = function(data) { if (data.errors != null) { alert("There was an error!"); } else { $("#content").text(data.message); } }; $.get('/users', success, 'json'); });
  • 41. Whitespace $(function() { def fibonacci success = function(data) { a = 0 if (data.errors != null) { b = 1 alert("There was an error!"); 100.times do } else { printf("%dn", a) $("#content").text(data.message); a, b = b, a + b } end }; end $.get('/users', success, 'json'); });
  • 42. Whitespace $(function() { def fibonacci a = 0 success = function(data) { b = 1 if (data.errors != null) { alert("There was an error!"); 100.times do } else { printf("%dn", a) $("#content").text(data.message); a, b = b, a + b } end }; end $.get('/users', success, 'json'); });
  • 43. Whitespace $ -> success = (data) -> if data.errors? alert "There was an error!" else $("#content").text(data.message) $.get('/users', success, 'json')
  • 44. Whitespace $(function() { var success; success = function(data) { if (data.errors != null) { return alert("There was an error!"); } else { return $("#content").text(data.message); } }; return $.get('/users', success, 'json'); });
  • 47. Conditionals if true doSomething() unless true doSomething()
  • 48. Conditionals if true doSomething() if true doSomething() doSomething() unless true unless true doSomething()
  • 49. Conditionals if true doSomething() if true doSomething() doSomething() unless true unless true doSomething() if true doSomething() else doSomethingElse()
  • 50. Objects/Hashes someObject = {conf: "RailsConf", talk: "CoffeeScript"} someObject = conf: "RailsConf" talk: "CoffeeScript" someFunction(conf: "RailsConf", talk: "CoffeeScript")
  • 51. Objects/Hashes var someObject; someObject = { conf: "RailsConf", talk: "CoffeeScript" }; someObject = { conf: "RailsConf", talk: "CoffeeScript" }; someFunction({ conf: "RailsConf", talk: "CoffeeScript" });
  • 52. Ranges a = [1..5] b = [1...5] c = [1..100] d = [100..1]
  • 53. Ranges a = [1..5] var a, b, c, d, _i, _j, _results, _results1; a = [1, 2, 3, 4, 5]; b = [1...5] b = [1, 2, 3, 4]; c = [1..100] c = (function() { _results = []; d = [100..1] for (_i = 1; _i <= 100; _i++){ _results.push(_i); } return _results; }).apply(this); d = (function() { _results1 = []; for (_j = 100; _j >= 1; _j--){ _results1.push(_j); } return _results1; }).apply(this);
  • 54. String Interpolation name = "RailsConf 2012" console.log "Hello #{name}" # Hello RailsConf 2012 console.log 'Hello #{name}' # Hello #{name}
  • 55. String Interpolation name = "RailsConf 2012" var name; console.log "Hello #{name}" name = "RailsConf 2012"; # Hello RailsConf 2012 console.log("Hello " + name); console.log 'Hello #{name}' # Hello #{name} console.log('Hello #{name}');
  • 56. Heredocs html = """ <div class="comment" id="tweet-#{tweet.id_str}"> <hr> <div class='tweet'> <span class="imgr"><img src="#{tweet.profile_image_url}"></span> <span class="txtr"> <h5><a href="http://twitter.com/#{tweet.from_user}" target="_blank">@#{tweet.from_user}</a></h5> <p>#{tweet.text}</p> <p class="comment-posted-on">#{tweet.created_at}</p> </span> </div> </div> """
  • 57. Heredocs var html; html = "<div class="comment" id="tweet-" + tweet.id_str + "">n <hr>n <div class='tweet'>n <span class= "imgr"><img src="" + tweet.profile_image_url + ""></ span>n <span class="txtr">n <h5><a href= "http://twitter.com/" + tweet.from_user + "" target= "_blank">@" + tweet.from_user + "</a></h5>n <p>" + tweet.text + "</p>n <p class="comment-posted-on">" + tweet.created_at + "</p>n </span>n </div>n</div>";
  • 58. Functions p = (name) -> console.log "Hello #{name}" p('RailsConf 2012')
  • 59. Functions var p; p = function(name) { return console.log("Hello " + name); }; p('RailsConf 2012');
  • 60. Functions p = (name)-> console.log "Hello #{name}" p('RailsConf 2012')
  • 61. Functions p = (name)-> console.log "Hello #{name}" CoffeeScript p('RailsConf 2012')
  • 62. Functions p = (name)-> console.log "Hello #{name}" CoffeeScript p('RailsConf 2012') p = ->(name) { puts "Hello #{name}" } Ruby 1.9 p.call('RailsConf 2012')
  • 63. Default Arguments createElement = (name, attributes = {}) -> obj = document.createElement name for key, val of attributes obj.setAttribute key, val obj
  • 64. Default Arguments var createElement; createElement = function(name, attributes) { var key, obj, val; if (attributes == null) { attributes = {}; } obj = document.createElement(name); for (key in attributes) { val = attributes[key]; obj.setAttribute(key, val); } return obj; };
  • 65. Splats* splatter = (first, second, others...) -> console.log "First: #{first}" console.log "Second: #{second}" console.log "Others: #{others.join(', ')}" splatter [1..5]...
  • 66. Splats* var splatter, __slice = [].slice; splatter = function() { var first, others, second; first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? __slice.call(arguments, 2) : []; console.log("First: " + first); console.log("Second: " + second); return console.log("Others: " + (others.join(', '))); }; splatter.apply(null, [1, 2, 3, 4, 5]);
  • 67. Loops & Comprehensions for someName in someArray console.log someName for key, value of someObject console.log "#{key}: #{value}"
  • 68. Loops & Comprehensions var key, someName, value, _i, _len; for (_i = 0, _len = someArray.length; _i < _len; _i++) { someName = someArray[_i]; console.log(someName); } for (key in someObject) { value = someObject[key]; console.log("" + key + ": " + value); }
  • 69. Loops & Comprehensions numbers = [1..5] console.log number for number in numbers
  • 70. Loops & Comprehensions var number, numbers, _i, _len; numbers = [1, 2, 3, 4, 5]; for (_i = 0, _len = numbers.length; _i < _len; _i++) { number = numbers[_i]; console.log(number); }
  • 71. Loops & Comprehensions numbers = [1..5] console.log number for number in numbers when number <= 3
  • 72. Loops & Comprehensions var number, numbers, _i, _len; numbers = [1, 2, 3, 4, 5]; for (_i = 0, _len = numbers.length; _i < _len; _i++) { number = numbers[_i]; if (number <= 3) { console.log(number); } }
  • 73. Loops & Comprehensions numbers = [1, 2, 3, 4, 5] low_numbers = (number * 2 for number in numbers when number <= 3) console.log low_numbers # [ 2, 4, 6 ]
  • 74. Loops & Comprehensions var low_numbers, number, numbers; numbers = [1, 2, 3, 4, 5]; low_numbers = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = numbers.length; _i < _len; _i++) { number = numbers[_i]; if (number <= 3) { _results.push(number * 2); } } return _results; })(); console.log(low_numbers);
  • 75. Classes class Employee emp = new Employee() emp.firstName = "Mark"
  • 76. Classes var Employee, emp; Employee = (function() { Employee.name = 'Employee'; function Employee() {} return Employee; })(); emp = new Employee(); emp.firstName = "Mark";
  • 77. Classes class Employee constructor: (@options = {}) -> salary: -> @options.salary ?= "$250,000" emp = new Employee() console.log emp.salary() # "$250,000" emp = new Employee(salary: "$100,000") console.log emp.salary() # "$100,000"
  • 78. Classes var Employee, emp; Employee = (function() { Employee.name = 'Employee'; function Employee(options) { this.options = options != null ? options : {}; } Employee.prototype.salary = function() { var _base, _ref; return (_ref = (_base = this.options).salary) != null ? _ref : _base.salary = "$250,000"; }; return Employee; })(); emp = new Employee(); console.log(emp.salary()); emp = new Employee({ salary: "$100,000" }); console.log(emp.salary());
  • 79. Extending Classes class Manager extends Employee constructor: -> super @options.salary ?= "$500,000" manager = new Manager() console.log manager.salary() # "$500,000"
  • 80. Extending Classes var Manager, manager, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; Manager = (function(_super) { __extends(Manager, _super); Manager.name = 'Manager'; function Manager() { var _base; Manager.__super__.constructor.apply(this, arguments); if ((_base = this.options).salary == null) { _base.salary = "$500,000"; } } return Manager; })(Employee); manager = new Manager(); console.log(manager.salary());
  • 81. Extending Classes class Manager extends Employee constructor: -> super @options.salary ?= "$500,000" salary: -> "#{super} + $10k" manager = new Manager() console.log manager.salary() # "$500,000 + $10k"
  • 82. Extending Classes var Manager, manager, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }; Manager = (function(_super) { __extends(Manager, _super); Manager.name = 'Manager'; function Manager() { var _base; Manager.__super__.constructor.apply(this, arguments); if ((_base = this.options).salary == null) { _base.salary = "$500,000"; } } Manager.prototype.salary = function() { return "" + Manager.__super__.salary.apply(this, arguments) + " + $10k"; }; return Manager; })(Employee); manager = new Manager(); console.log(manager.salary());
  • 83. Bound Functions class User constructor: (@name) -> sayHi: -> console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  • 84. Bound Functions about to execute callback... Hello undefined ...executed callback about to execute callback... Hello undefined ...executed callback
  • 85. Bound Functions class User constructor: (@name) -> sayHi: -> console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  • 86. Bound Functions class User constructor: (@name) -> sayHi: -> console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  • 87. Bound Functions class User constructor: (@name) -> sayHi: => console.log "Hello #{@name}" bob = new User('bob') mary = new User('mary') log = (callback)-> console.log "about to execute callback..." callback() console.log "...executed callback" log(bob.sayHi) log(mary.sayHi)
  • 88. Bound Functions about to execute callback... Hello bob ...executed callback about to execute callback... Hello mary ...executed callback
  • 89. Bound Functions class User constructor: (@name) -> sayHi: => console.log "Hello #{@name}"
  • 90. Bound Functions var User, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; User = (function() { User.name = 'User'; function User(name) { this.name = name; this.sayHi = __bind(this.sayHi, this); } User.prototype.sayHi = function() { return console.log("Hello " + this.name); }; return User; })();
  • 91. FINALLY One of my favorite features
  • 92. Existential Operator if foo? console.log "foo" console.log "foo" if foo?
  • 93. Existential Operator if (typeof foo !== "undefined" && foo !== null) { console.log("foo"); } if (typeof foo !== "undefined" && foo !== null) { console.log("foo"); }
  • 94. WAIT! IT GETS BETTER!
  • 96. Existential Operator console?.log "foo" if (typeof console !== "undefined" && console !== null) { console.log("foo"); }
  • 97. Existential Operator if currentUser?.firstName? console.log currentUser.firstName
  • 98. Existential Operator if currentUser?.firstName? console.log currentUser.firstName if ((typeof currentUser !== "undefined" && currentUser !== null ? currentUser.firstName : void 0) != null) { console.log(currentUser.firstName); }
  • 99. What Didn’t I Cover? Scoping Security Strict Mode Fixes common ‘mistakes’ Operators The `do` keyword Plenty more!
  • 101. Thank You myName = "Mark Bates" you.should buyBook("Programming in CoffeeScript") .at("http://books.markbates.com") you.should followMe(@markbates)

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n