Saturday, January 5, 2013

CoffeeScript data types and functions

CoffeeScript's golden rule is "It's just JavaScript". As seen, in the previous entry, it compiles to a 1-to-1 equivalent of JavaScript. This also means that CoffeeScript's data types are also limited to what JavaScript has. These are strings, numbers, booleans, arrays, objects, nulls and undefined values. But CoffeeScript has a couple of pretty cool stuff baked for data types, especially strings. Here is a pair of examples:

name = "Jay" // CoffeeScript doesn't need a var prefix 
greet = "Hello, #{name}" // String interpolation
                         // Result: Hello, Jay

grade = 88.43 
withHonors = 100 <= grade > 85 // chained comparisons
                               // Result: true

songNotes = ["do", "re", 
             "mi", "fa", 
             "so"] // just an array but CoffeeScript knows how to deal with new lines

Also, CoffeeScript takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself.

There are a lot more cool/useless stuff baked into CoffeeScript variables but to really use them you need functions. In JavaScript, functions are needed for almost anything. Its the same in CoffeeScript. CoffeeScript just declares functions differently - more lisp/scala like.
// Here is a function without a paramter
foo -> alert('foobar')  // foo is the function name
                        // the part after the "->" is the body of the function

// Here is a function with a parameter
square = (x) -> x * x  

// Here is a function with default value on a parameter
fill = (container, liquid = "coffee") ->
  "Filling the #{container} with #{liquid}..."

No comments:

Post a Comment