Underneath that awkward Javaesque patina, JavaScript has always had a gorgeous heart! h<ps://github.com/jashkenas/coffeescript Spyros Ioakeimidis | TechTalk 21/10/2013
May 10, 2015
Underneath that awkward Java-‐‑esque patina, JavaScript has always had a gorgeous heart!
h<ps://github.com/jashkenas/coffee-‐‑script
Spyros Ioakeimidis | TechTalk 21/10/2013
Intro
static analysis by design
CoffeeScript code compiles one-‐‑to-‐‑one to JavaScript
no runtime checking (interpretation at runtime)
literate mode, you can write markdown document, which can contain executable CoffeeScript code
2
Compile *.coffee
coffee -‐‑o lib/ -‐‑cw src/ (and sub-‐‑directories)
in the alphabetical order of the files (as they are found in the file system)
coffee -‐‑j lib/main.js -‐‑cw src/
merge *.coffee files into one merged.js file, again in the alphabetical order the compiler finds them in the file system
it can also be used in strict mode (DEBUG = True)
3
write main.coffee
use main.coffee in html
client requestsmain.coffee
compile to main.js
main.js is served
Serve *.coffee
(1) compile *.coffee file in runtime when it is requested (and if there is a newer version), cache does not work as usual (gets the same file again, though it is not slower)
4
Serve *.coffee
(2) compile during development, generate *.js files and serve those, include them in templates (precompile phase)
5
write main.coffee
compile main.coffee
use main.js filein index.html
serve main.jsfile
client requestsmain.js
Serve *.coffee
django-‐‑compressor
<script type="ʺtext/coffeescript"ʺ src="ʺ{% static 'ʹrewards.coffee'ʹ %}"ʺ></script>
when a file is requested, it is compiled, a CACHE directory is created (if it does not exist) and the *.js files are stored and served from in there
Stitch, NodeJS, or Rails
automatic runtime compile is included, and it is transparent
in production, Rails will write the compiled output to disk, ensuring it'ʹs cached and fast to serve
6
CoffeeScript
whitespace is significant
no semicolons
it removes global variables
need to be careful with functions and parens, e.g.
alert inspect aalert inspect # gives error, is it a function or an argument?alert inspect(a) # this is beKer
7
CoffeeScript
aliases for this is @ and for accessing the prototype is ::
solves the issues with “with” statements, reserved keywords, Number property lookups
fixes the equality comparisons ambiguity, by using the (===) strict equality operator, e.g. "ʺ"ʺ == "ʺ0"ʺ // false 0 == "ʺ"ʺ // true 0 == "ʺ0"ʺ // true false == "ʺfalse"ʺ // false
...
8
*example taken from [1]
CoffeeScriptfunction definitions, CoffeeScript uses only function expressions and discards completely declarative functions e.g. expression = function() { } instead of function declaration() { }
offers cross-‐‑browser compatibility
but there are other things that CoffeeScript can'ʹt fix
eval
typeof
same for instanceof
delete, parseInt()
9
CoffeeScript{ functions, use of parens }
10
Console:27
CoffeeScript{ objects, arrays, splash..., string interpolation }
11
Console:Gold: Michael Phelps in 9.68Silver: Liu Xiang in 10.56Rest: Yao Ming,Allyson Felix,...
CoffeeScript{ loops, comprehensions, slicing, when, isnt, unless }
12
Console:PY :)
CoffeeScript{ iterate over object properties }
13
Console:max is 10,ida is 9,tim is 11
CoffeeScript{ while, conditional assignment }
14
Console:5 little monkeys, jumping on the bed. One fell out and bumped his head.4 little monkeys, jumping on the bed. One fell out and bumped his head.3 little monkeys, jumping on the bed. One fell out and bumped his head.2 little monkeys, jumping on the bed. One fell out and bumped his head.1 little monkey, jumping on the bed. One fell out and bumped his head.
CoffeeScript{ do, loop to generate functions }
15
Console:Reading file: file-1 compiled as <file-1, ...file contents...>Reading file: file-2 compiled as <file-2, ...file contents...>
CoffeeScript{ existential operator }
16
Console:9715 ZM
CoffeeScript{ classes, inheritance, destructuring assignment }
17
Console:char0: firstName -> Tomchar0: lastName -> and JerryCartoon Report:Tom and Jerry received 10!char1: firstName -> Amazingchar1: lastName -> SpidermanSuperhero Report:Amazing Spiderman received 1000!
CoffeeScript{ instead of typeof, we can use a trick }
18
CoffeeScript{ another example of destructuring assignment }
19
Console:City: Groningen, NL Temp: -10 Forecast: Mostly Snow
CoffeeScript{ using the window to create top level variables }
20
CoffeeScript{ function binding with the fat arrow => }
21
Console:Purchase for customer 345 and cart cart_45654
CoffeeScript{ switch statements, chained comparisons }
22
Console:Grade: D+
CoffeeScript{ exceptions }
23
Console:Ops exception ReferenceError: Undefined is not definedfinally...
CoffeeScript{ use of mixins when inheritance is not suited }
24
CoffeeScript{ use of mixins when inheritance is not suited }
25
Console:Finding id 1Creating...Saving...(when the button with class ‘.show’ is pressed)Showing user with id 1
CoffeeScript{ or= }
26
Console:empty something
Share Objectsexports = thisexports.variable = "ʺtest"ʺ
or if Node.js, or Stitch is used with CommonJS which provides modules, e.g.
# app/models/user.coffeemodule.exports = class User constructor: (@name) -‐‑>
# app/app.coffeeUser = require("ʺmodels/user"ʺ)
27
JS vs CSless code to write! the example with the fictional character class was:
100 loc in JS, 50 loc in CS
far more readable, less complex, and more maintainable
CoffeeScript tends to run as fast, or faster than hand-‐‑wri<en JavaScript
however, CoffeeScript introduces another layer..
no big community yet.. but it is ge<ing bigger :)
28
29
CoffeeScriptAngularJS
&
Testing
unit testing and Behaviour-‐‑driven Development (BDD) with the popular framework Jasmine
assaf'ʹs Zombie.js, a headless, full-‐‑stack, faux-‐‑browser testing library for Node.js
Testing with CoffeeScript: h<p://goo.gl/U67oKU
30
Performance
test of operations on a million floating point numbers
CoffeeScript -‐‑> 0.164s
CPython -‐‑> 0.603s
more than 3.5x faster
of course C++ is 10x to 30x faster :)
31
*algorithms taken from [3]
Performance
test on the 8 queens problem, more info can be found in [4]
CoffeeScript -‐‑> 0.034s
CPython -‐‑> 0.455s
more than 13x faster
32
*algorithms taken from [3]
Used on...several open-‐‑source projects
brunch: HTML5 applications made easyh<ps://github.com/brunch/brunch
zombie: a headless, full-‐‑stack, faux-‐‑browser testing library for Node.jsh<ps://github.com/assaf/zombie
underscore.coffee: a port of the Underscore.js library of helper functionsh<p://coffeescript.org/documentation/docs/underscore.html
33
What does thefuture hold?
new features are coming with the new EcmaScript6 [5]
(define block-‐‑local vars), destructuring, parameter default values, rest (splash...), spread, proxies, weak map, generators, iterators, array and generator comprehension, binary data, class syntax, with extends, prototype, and super, modules, quasis: multiline, substitution-‐‑ready strings with extensibility
experimental javascript can be tried in Chrome by enabling the Experimental JavaScript flag onchrome://flags/#enable-‐‑javascript-‐‑harmony
34
*you can read more in [6]
Little Book on CoffeeScript
CoffeeScript is ge<ing much wider use and integration, such as being a default in Rails 3.1. Now is definitely the time to jump on the CoffeeScript train. The time you invest in learning about the language now will be repaid by major time savings later.
35
“
Let’s write someCoffeeScript
[2] CoffeeScript recipes for the community by the community, h<p://coffeescriptcookbook.com/
References[1] h<p://bonsaiden.github.io/JavaScript-‐‑Garden/#types.equality
[3] Smooth CoffeeScript, h<p://goo.gl/RjT74k
[4] Eight Queens Puzzle, h<p://en.wikipedia.org/wiki/Eight_queens_puzzle
[5] h<p://espadrine.github.io/New-‐‑In-‐‑A-‐‑Spec/es6/
[6] h<p://gaslight.co/blog/does-‐‑coffeescript-‐‑have-‐‑a-‐‑future
[7] Li<le Book on CoffeeScript, h<p://arcturo.github.io/library/coffeescript/