# FunctionsmyFunction = -># Translates to:function(){# Functions with argumentsmyFunction = (arg) -># Translates to:function(arg){# No semicolons are needed in CoffeeScript(CS).# Maintaining the context of 'this' with the 'fat arrow'myFunction = (arg) =># Operatorsis# Translates to:\===not# Translates to:!isnt# Translates to:!==and# Translates to:&&or# Translates to:||# Single-line "if" statementsifxtheny# Splat operator(…)# For loopsmyFunction(item)foriteminarray# While loopswhilenum-=1# Alias for prototypeBob::hey# Translates to:Bob.prototype.hey# Executing functions immediately with the keyword dotype = do-># Code is then private and cannot be accessed in the future.# Chained comparison syntaxa<b<c# Null ChecksblackKnight.getLegs()?.kick()# Won’t call kick() if getLegs is false.blackKnight.getLegs().kick?()# Won’t call kick() if kick() is null or not a function.
# Declaring a variablestring = "Foo bar baz"# Inline "if" statmentsconsole.log("Hello, world!")iftrue# "unless" statmentsconsole.log("Hello, world!")unlessfalse# “==“ converts to “===“, “!=“ converts to “!==“1==2# Evaluates as "1 === 2"1!=2# Evaluates as "1 !== 2"# String Interpolationcode = "Hello"console.log(“#{code}, world!”)# Defining an object literal without curly bracketsobj = one: 1,two: 2# Conditional assignment operatorvariable||=2# Is the same as:variableor=2# You can also use:variable?=2# Instance variable@snake# Evaluates to:this.snake# Ranges[1..5]# Slice[1,2,3,4,5][0..1]=>[1,2]# Or:“mystring”[1..4]# Checking Contentarr[“a”,“b”,“c”];“a”inarr# Returns true.# Like Ruby #include?# Existential Operatorpraiseifbrian?# Only returns false for null or undefined (*NOT* for “” or 0).# Like .nil? in Ruby.# Can also be used for ||.
Classes
CoffeeScript - Classes
123456789101112131415161718192021
# Declaring ClassesclassAnimal# Instantiating Classesanimal = newAnimal(args)# Instantiating Classes With Instance Variablesconstructor: (arg) ->@name = name# Or the shorthand:contructor: (@arg) -># InheritanceclassParrotextendsAnimal# In Ruby, this would be: class Parrot < Animal
# eachmyFunction(item)foriteminarray# each with indexforname,iinnames# mapresult = (item.nameforiteminarray)# selectresult = (item.nameforiteminarraywhenitem.name==“test”)# includesincluded = “alongteststring”.indexOf(“test”)isn’t-1# iteratingalert(“#{key}#{value}) for key, value of object# min/maxMath.max[1,15,2312,42]…=>2312
eval()# Executes a piece of Javascript code in local scope. Throws complier off.# Insecure: this opens code for injection attacks.# Instead of:model= eval(modelName)# Use:model = window[modelName]typeof()# Only useful to check if something is undefined, otherwise results are inconsistent.# Instead of:typeof(obj)# Use:Object.prototype.toString()# Use duck typing with existential operator to try using an object whose type you don’t know.instanceof()# Broken, like typeof(). Avoid use.delete# Can be used safely to remove properties within objects, but not to delete functions or variables.# Assign them to null instead.parseInt()# Pass it a base to ensure it works as expected.parseInt(‘num’,10)
Good Parts
Semicolons - don’t need them in CoffeeScript!
Global variables - CS automatically declares var to prevent them!
Reserved words - CS automatically escapes them!
Type coercion - CS turns “==” into “===”
Declarative functions - although you can call a function before it’s defined in JS, CS removes this problematic behavior.
Number property lookups - in JS, “.” gets interpreted as a decimal. In CS it gets changed to “..”, to access a property.
Linting - CS has built in linting, which can be called with
“coffee lint index.coffee”