CoffeeScript is a programming language that compiles to JavaScript. It addresses issues in JavaScript like global variables, semicolons, and reserved words by generating proper JavaScript code. CoffeeScript also improves control flow, functions, classes, and other aspects of JavaScript. It allows everything to be an expression, uses chained comparisons, and string interpolation to make code more concise and readable.
18. var message = “hola”;!
!
function saluda() {!
return message;!
}
var message = “adios”;!
!
function despidete() {!
return message;!
}
Global variables
Si ambos ficheros están “cargados”,
¿Cuál es la salida esperada en cada
función?
19. Global variables
CoffeeScript no crea variables globales de
forma implícita
(function() {!
var message, saluda;!
!
message = "hola";!
!
saluda = function() {!
return message;!
};!
}).call(this);
message = "hola"!
!
saluda = () -> !
message
32. switch fall through
Bond = (input) -> !
switch input!
when 'Sean Connery', 'Daniel Craig'!
'Fucking crack'!
when 'Roger Moore'!
'A bit boring'
var Bond;!
!
Bond = function(input) {!
switch (input) {!
case 'Sean Connery':!
case 'Daniel Craig':!
return 'Fucking crack';!
case 'Roger Moore':!
return 'A bit boring';!
}!
};!
Todas las opciones acaban con un return
35. Control de flujo
mood = greatlyImproved if singing!
!
if happy and knowsIt!
clapsHands()!
else!
showIt()!
!
date = if friday then sue else jill!
!
isToday = yes unless yesterday or tomorrow!
!
// -----------------------------------------------------!
!
cholesterol = 127!
!
healthy = 200 > cholesterol > 60!
Chained comparisons
Everything a expression
36. Control de flujo
Bond = (input) -> !
switch input!
when 'Sean Connery', 'Daniel Craig'!
'Fucking crack'!
when 'Roger Moore'!
'A bit boring'!
else!
'No comments'
37. Bucles
# Health conscious meal.!
foods = ['broccoli', 'spinach', 'chocolate']!
eat food for food in foods when food isnt 'chocolate'!
!
countdown = (num for num in [10..1])!
!
# Econ 101!
if this.studyingEconomics!
buy() while supply > demand!
sell() until supply > demand!
!
while age < 18!
canNotSmoke()!
canNotDrink()
39. Operators & aliases
CoffeeScript JavaScript
is ===
isnt !==
not !
and &&
or ||
true, yes, on true
false, no, off false
@, this this
of in
in no JS equivalent