Essence of CoffeeScript Key Fundamentals Punctuation is usually optional, so skip it ;}),console.log('Hi');console.log 'Hi'nickname = prompt "What's your nickname?" console.log 'Hi ' + nicknameEnter the example CoffeeScript code (above) into the editor (below).Press the run button to see results in the console.Notice that ()'s can be skipped and you don't need ; at the end of a line. Use indentation instead of { } curly bracesdate = new Date() hour = date.getHours() if (hour > 17) { now = 'night' } else { now = 'day' }date = new Date() hour = date.getHours() if hour > 17 now = 'night' else now = 'day' console.log "It is now #{now} time."Write an if/else statement using indentation.Notice that the structure of the code contains valuable information.This is very similar to the way python works. Or haml. Or sass. Every expression returns a valuedate = new Date() hour = date.getHours() now = if hour > 17 then 'night' else 'day' console.log "It is now #{now} time."Check it out - an if statement actually returns a value.This is very similar to the way ruby works.Get a hands-on feeling of this by entering the example code into the editor. Never specify varvar cost = 9.99 var total = '$ ' + cost + ' is your total cost.'cost = 9.99 total = "$ #{cost} is your total cost."Well, practice not writing var.Seriously though, its pretty nice that there won't be any bugs because of a forgotten var. Some Useful Tips Read a line from right to leftconsole.log 'Hi ' + prompt "What's your nickname?"Predict what the example code above will do by reading it from right to left.Enter it into the editor and run it to see if you got it exactly right.If necessary, adjust your prediction and run it again :) Use punctuation wherever it adds readabilityconsole.log 'Hi ' + (prompt "What's your nickname?") console.log 'Hi ' + prompt("What's your nickname?")Experiment with different placement of parenthesis.Find a style that enhances the readability of your code for others. Object literals are all over the placevar options = { readonly: true, theme: 'solarized' } var theme = { color: { text: 'blue', background: 'white' }, font: { family: 'SourceCode Pro', size: '16px' } }options = readonly: true, theme: 'solarized' theme = color: text: 'blue' background: 'white' font: family: 'SourceCode Pro' size: '16px' console.log 'options are ', options console.log 'colorTheme is ', theme.color console.log 'font family is ', theme.font.family Become familiar with an object literal (or hash) without its punctuation.The : indicates a key: value pair.Key value pairs need to be separated with a comma when on the same line.Key value pairs don't need comma separation when on their own line.Key value pairs that belong to the same hash are indented at the same level. A Function Is This Way -> Use dash rocket -> to define a functionvar reportStatus = function(msg){ console.log('Status:', msg); };reportStatus = (msg)-> console.log 'Status: ', msg reportStatus 'ok'When defining a function:
send (arguments...) into -> function body
Define the reportStatus function (as in the example above) and call it.
A function with no arguments doesn't need ()getHostname = -> console.log location.hostname getHostname()Define the getHostname() function above and call it.Notice that () is needed to call the function, but not to define it. A function automatically returns its final valuegetHostname = -> location.hostname console.log getHostname()Enter the code above into the editor and run it.Notice that the function returns its final value.This is similar to the way ruby works. Indent the function bodyreportRootURL = -> protocol = location.protocol hostname = location.hostname console.log "#{protocol}//#{hostname}" reportRootURL()Define the reportRootURL function and call it. Get used to passing a functionquoteCallback = (quote)-> console.log quote apiEndpoint = 'https://api.github.com/zen' jQuery.get apiEndpoint, quoteCallbackGet a zen coding quote from the Github API using the example code.Pair with someone to understand the significance of each line.
Some Conditional Love The body of an if can come firsttimeOfDay = 'morning' if hour < 11getTimeOfDay = (hour)-> timeOfDay = 'morning' if hour < 11 # +++ ToDo set timeOfDay = 'AFTERNOON' timeOfDay = 'night' if hour > 17 timeOfDay reportTimeOfDayForHour = (hour) -> console.log "at #{hour}, it is #{getTimeOfDay hour}" reportTimeOfDayForHour 9 reportTimeOfDayForHour 12 reportTimeOfDayForHour 20 Run the given code and notice that timeOfDay is undefined at 12Complete the function getTimeOfDay to return 'AFTERNOON' when hour is 12Run the corrected code.Why is timeOfDay the last line of the getTimeOfDay function? Use unless to flip an if elsetimeOfDay = 'night' unless hour < 11askForGeoLocation = -> return alert 'Seriously? You gotta update your browser!' unless navigator.geolocation alert 'Your browser is about to ask you to allow geolocation' navigator.geolocation.getCurrentPosition positionCallback positionCallback = (position)-> point = position.coords console.log "Lat: #{point.latitude}, Lng: #{point.longitude}" askForGeoLocation()Get the geolocation of your browser using the example code. The Existential ? Operator Use ? to check if something existsconsole.log 'unicorns are not real!' unless unicornsExist console.log 'unicorns are not real!' unless unicornsExist? unicornsExist = false console.log 'unicorns are real!' if unicornsExist console.log 'unicorns are real!' if unicornsExist?The existential operator is one of the coolest features in CoffeeScript.Run each of the above lines one at a time.Notice that the existential operator can be used to check if something exists.Observe which statements create errors.Observe that ? can be used to avoid errors all together.Observe that the ? operator is not a replacement for boolean logic.Observe that the last line is a bug. Use ? to set default valuessetProfile = (profile)-> profile ?= {} profile.name ?= 'guest' console.log 'profile:', profile setProfile() setProfile age: 25 setProfile name: 'misty'Enter the setProfile function into the editor.Use console.log to call it with different hash values, or with no value at all. Use ? to call a function only if it existsbarn = horse: run: ()-> 'gallop' for i in [0..3] console.log barn.horse.run() console.log barn.horse.fly() console.log barn.horse.fly?() Define barn in the editor like in the example code.Run the console.log statements in the console.What happens if you run the same statements without ? Use ? to soak up errors in chainconsole.log h.run?() console.log h.fly?() console.log p.run?() console.log p.fly?() barn = horse: run: ()-> 'gallop' for i in [0..3] h = barn.horse p = barn.pig Run the console.log statements from the exampe above in the console below.Add ? where necessary to soak up any errors. Some Loopy Situations Use in to loop through an arrayprintDigits = ()-> digits = [0..9] for digit in digits console.log 'digit: ', digitEnter the example code above into the editorcall printDigits() from the console Use of to loop through a hashreportTheme = ()-> theme = text: 'blue', button: 'red' for key, value of theme console.log "#{key} is set to #{value}"Enter the example code above into the editorCall reportTheme() from the console The body of a loop can come firstdigits = [0..9] console.log i for i in digits theme = {text: 'blue', button: 'red'} console.log key,'=', val for key,val of themeEnter the example code above into the console A loop retuns an array oddDigits = (1 + i*2 for i in [0..4])Run the example code in the console to see that oddDigits is actually an array of values. Working With Class Defining a class is simpleclass Mutant fight: (badGuy)-> 'Spin a Web onto ' + badGuy spidy = new Mutant spidy.fight('Lizard')Define the Mutant class in the editorCreate 'spidy' as an instance of Mutant in the console and have him fight Sandman. this has an alias: @class Mutant superPower: 'do nothing' fight: (badGuy)-> @superPower + ' onto ' + badGuy spidy = new Mutant spidy.fight('Boomerang') spidy.superPower = 'Spin web' spidy.fight('Boomerang') Define the Mutant class in the editor.Create an instance of spidy and use the instance in the console. Use a constructor for initializationclass Mutant superPower: 'do nothing' constructor: (power) -> @superPower = power fight: (badGuy)-> @superPower + ' onto ' + badGuy spidy = new Mutant 'spin web' spidy.fight 'SandMan'Define the Mutant class in the editor.Create an instance of spidy in the console and have him fight Sandman. Inheriting from a Class is Simpleclass Mutant superPower: 'do nothing' constructor: (power) -> @superPower = power fight: (badGuy)-> @superPower + ' onto ' + badGuy class NinjaTurtle extends Mutant constructor: () -> super('Kung Fu') raphael = new NinjaTurtle raphael.fight('Shredder') Define the Mutant class in the editor.Create an instance of spidy and use the instance in the console.