Busy Developer's Guide to CoffeeScript

ted@tedneward.com | Blog: http://blogs.tedneward.com | Twitter: tedneward | Github: tedneward | LinkedIn: tedneward

Objectives

Get a good introduction to CoffeeScript

CoffeeScript Intro

Getting to know CoffeeScript

Conceptuals

CoffeeScript is essentially a "Ruby" for JavaScript

Install

Installing CoffeeScript

Usage

Useful command-line parameters

Install

Installing CoffeeScript Redux (2.0)

Basics

Basic assignment and operations

# Assignment:
number   = 42
opposite = true
    
# String interpolation:
author = "Wittgenstein"
quote  = "A picture is a fact. -- #{ author }"
sentence = "#{ 22 / 7 } is a decent approximation of pi"
    
# Multiline strings:
mobyDick = "Call me Ishmael. Some years ago --
  never mind how long precisely -- having little
  or no money in my purse..."
    
# Block strings:
html = """
       <strong>
         cup of coffeescript
       </strong>
       """

Scoping

Lexical scoping

outer = 1
    
changeNumbers = ->
  inner = -1
  outer = 10
    
inner = changeNumbers()

Conditionals

Conditionals

mood = greatlyImproved if singing
if happy and knowsIt
  clapsHands()
else
  showIt()
    
date = if friday then sue else jill
    
switch day
  when "Mon" then go work
  when "Fri", "Sat"
    if day is bingoDay
      go dancing
  when "Sun" then go church
  else go work
    
grade = switch
  when score < 60 then 'F'
  when score < 70 then 'D'
  else 'PASS'
# grade == 'PASS'

Conditional Operators

Operator set

    
launch() if ignition is on           # is : ====
    
volume = 10 if band isnt SpinalTap   # isnt : !==
    
partyOn() if homeworkDone is true    # true, yes, on: truthy
partyOn() unless answer is no        # false, no, off : falsy
    
winner = yes if pick in [47,92,13]   # in : === or === or ===
    
evaluation = 5 if speaker is funny or
  speaker is smart or
  audience is reallyDrunk

Expressions

Everything is an expression

eldest = if 24 > 21 then "Liz" else "Ike"
    
# Assignment can be used to init new variables
six = (one = 1) + (two = 2) + (three = 3)
    
# While loop is also an expression
num = 6
lyrics = while num -= 1
  "#{num} little monkeys, jumping on the bed.
    One fell out and bumped his head."
    
# Even try/catch yields a value
alert(
  try
    nonexistent / undefined
  catch error
    "And the error is ... #{error}"
)

Arrays

Arrays

song = ["do", "re", "mi", "fa", "so"]
    
singers = {Jagger: "Rock", Elvis: "Roll"}
    
bitlist = [
  1, 0, 1
  0, 0, 1
  1, 1, 0
]
    
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
start   = numbers[0..2]
middle  = numbers[3...-2]
end     = numbers[-2..]
copy    = numbers[..]
    
numbers[3..6] = [-3, -4, -5, -6]

Loops

Loops and Comprehensions

# Simple comprehension
print food for food in ['toast', 'cheese', 'wine']
    
# Use multiple iterators if desired
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
print i + 1, dish for dish, i in courses
    
# Filtered comprehension
foods = ['broccoli', 'spinach', 'chocolate']
print food for food in foods when food isnt 'chocolate'
    
shortNames = (name for name in foods when name.length < 5)
    
# Range
countdown = (num for num in [10..1])
evens = (x for x in [0..10] by 2)

Functions

Functions

square = (x) -> x * x
cube   = (x) -> square(x) * x
    
print = (msg) -> console.log(msg)
    
print(cube(3))
print cube 3
    
fill = (container, liquid = "coffee") ->
  "Filling the #{container} with #{liquid}..."
    
print fill "cup"

'Splats' (Varargs)

Variable argument lists

gold = silver = rest = "unknown"
    
awardMedals = (first, second, others...) ->
  gold   = first
  silver = second
  rest   = others
    
contenders = [
  "Michael Phelps", "Liu Xiang"
  "Yao Ming", "Shawn Johnson"
]
    
awardMedals contenders...

Objects

Object definitions

math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x
    
singers = {Jagger: "Rock", Elvis: "Roll"}
    
kids =
  brother:
    name: "Max"
    age:  11
  sister:
    name: "Ida"
    age:  9
    
alert "I knew it!" if elvis?

Objects

Object comprehensions

# A simple object of name/age pairs
yearsOld = max: 10, ida: 9, tim: 11
    
# Result is an array of interpolated strings
ages = for child, age of yearsOld
  "#{child} is #{age}"

Classes

Class definitions

class Animal
  constructor: (@name) ->
    
  move: (meters) ->
    alert @name + " moved #{meters}m."
    
class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5
    
class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45
    
sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
    
sam.move()
tom.move()

Literate

CoffeeScript can also be written as "literate"

Summary

CoffeeScript is a "cleaned-up" JavaScript

Credentials

Who is this guy?