CoffeeScript - The Beautiful Way To Write Javascript
CoffeeScript - The Beautiful Way To Write Javascript
The
Beau1ful
Way
to
Write
JavaScript
by
amir
salihefendic
-‐
amix@amix.dk
-‐
amix.dk
My
history
with
JavaScript
• WriDen
more
than
50.000
lines
of
JavaScript
function f(n) {
var s= 0;
if(n == 0) return(s);
if(n == 1) {
s += 1;
return(s);
}
else {
return(f(n - 1) + f(n - 2));
}
}
Example
of
Beau1ful
Code
function fib(n) {
return n<2 ? n : fib(n-1) + fib(n-2)
}
or
function fib(n) {
if (n < 2)
return n
return fib(n-2) + fib(n-1)
}
Is
it
possible
to
write
beau1ful
JavaScript?
• JavaScript
is
very
dynamic
and
is
a
lot
closer
to
Lisp
than
C/Java,
but
it
has
a
C/Java
syntax
• CoffeeScript
is
an
aDempt
to
expose
the
good
parts
of
JavaScript
in
a
simple
way
author = "Wittgenstein"
quote = "A picture is a fact. -- #{ author }"
mobyDick = "Call me Ishmael. Some years ago -
never mind how long precisely -- having little
or no money in my purse, and nothing
particular..."
CoffeeScript
Highlight
Inheritance
made
easy
class Animal
constructor: (@name) ->
move: (meters) ->
alert "#{ @name } moved #{meters} m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
CoffeeScript
Highlight
Solving
this
nightmare
loader.prototype.loadStuff = function() {
this.state = 'loading';
$.get('getStuff', function(data) {
//this is not what we think it is...!
this.state = 'loaded';
});
};
source
Extended
usage
of
CoffeeScript
Domain
Specific
Languages
(DSL)
Ac1veRecord’s
DSL
in
CoffeeScript
Rails
Ac1veRecord
DSL
lets
you
easily
express
rela1onships
between
model
classes