ted@tedneward.com | Blog: http://blogs.tedneward.com | Twitter: tedneward | Github: tedneward | LinkedIn: tedneward
Syntax
Semantics
Usage
CoffeeScript is essentially a "Ruby" for JavaScript
Syntax is vaguely Ruby-inspired
Dynamic/untyped type system
Some functional concepts embedded
Installing CoffeeScript
CoffeeScript is a Node-based environment
CoffeeScript is an npm package
npm install -g coffee-script
May need to run with sudo/admin privileges
Verify: "coffee --version"
Useful command-line parameters
--compile: .coffee -> .js compile
--watch: watch for changes, recompile on demand
--output DIR: write compiled .js files to DIR
--print: print resulting JS to stdout
--interactive: REPL
--nodes: lex, parse, print the parse tree
Installing CoffeeScript Redux (2.0)
CoffeeScriptRedux is a complete rewrite of CoffeeScript
"with proper compiler design principles"
Mostly a drop-in replacement
but there are some changes
Also an npm package
npm install -g coffee-script-redux
Install one, or the other, not both
In time, this should supplant the other
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> """
Lexical scoping
outer = 1 changeNumbers = -> inner = -1 outer = 10 inner = changeNumbers()
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'
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
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
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 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
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"
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...
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?
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}"
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()
CoffeeScript can also be written as "literate"
.litcoffee
file extension
Write a Markdown document, with CS in indented blocks
CS will ignore the document, compile the blocks
Part of the compiler is written this way (!)
Syntax is somewhat Ruby-inspired
Semantics are mostly all still JavaScript-based
Usage is minimal overhead for JS-based workflows
Overall, it's exactly what it aspires to be
Who is this guy?
Architect, Engineering Manager/Leader, "force multiplier"
Principal -- Neward & Associates
http://www.newardassociates.com
Educative (http://educative.io) Author
Performance Management for Engineering Managers
Author
Professional F# 2.0 (w/Erickson, et al; Wrox, 2010)
Effective Enterprise Java (Addison-Wesley, 2004)
SSCLI Essentials (w/Stutz, et al; OReilly, 2003)
Server-Based Java Programming (Manning, 2000)