Intro to CoffeeScript

Alex LaFroscia

@alexlafroscia

What it is

  • ​"A little language that compiles to JavaScript"
  • A nice way to expose the good parts of JavaScript, which are often hidden under an awkward syntax
  • A way to write good, clean code

Functions​ and Variables

JavaScript

var cube, square, add;

square = function(x) {
  return x * x;
};

cube = function(x) {
  return square(x) * x;
};

my_function = function(x, y) {
  var a, b;
  a = cube(x);
  b = square(y);
  return a + b;
};
  • Variables initialized
  • Keywords
    • function
    • var
    • return
  • Parenthesis
  • Semicolons
  • Brackets

CoffeeScript

square = (x) -> x * x

cube = (x) -> square(x) * x

my_function = (x, y)->
  a = cube x
  b = square y
  a + b
  • Use variables wherever they're needed
  • No keywords
  • Different function syntax
  • Optional parenthesis
  • No semicolons or brackets

 

Net result: Less code!

Arrays and Objects

JavaScript

var array, countNumbers, sayKeys;

array = [1, 2, 3, 4, 5];

object = {
  name: 'Alex',
  age: 19,
  job: 'programmer'
};

countNumbers = function(arr) {
  var int, i, len;
  for (i = 0, len = arr.length; i < len; i++) {
    int = arr[i];
    console.log(int);
  }
};

sayKeys = function(obj) {
  var key, value;
  for (key in obj) {
    value = obj[key];
    console.log("" + key + ": " + value);
  }
};

countNumbers(array);

sayKeys(object);
array = [1, 2, 3, 4, 5]

object =
  name: 'Alex'
  age: 19
  job: 'programmer'

countNumbers = (arr)->
  for int in arr
    console.log int

sayKeys = (obj)->
  for key,value of obj
    console.log "#{key}: #{value}"


countNumbers array

sayKeys object

CoffeeScript

Custom Classes

JavaScript

var Student, alex;

Student = (function() {
  function Student(options) {
    this.name = options.name,
    this.age = options.age,
    this.job = options.job;
  }

  Student.prototype.introduce = function() {
    return alert("Hello, I'm " + this.name);
  };

  return Student;

})();

alex = new Student({
  name: 'Alex',
  age: 19,
  job: 'programmer'
});

alex.introduce();

CoffeeScript

class Student
  constructor: (options)->
    {@name, @age, @job} = options

  introduce: ->
    alert "Hello, I'm #{@name}"


alex = new Student
  name: 'Alex'
  age: 19
  job: 'programmer'

alex.introduce()   # Hello, I'm Alex

Other Benefits of CoffeeScript

Existential Operator

alex = new Student
    name: 'Alex'
    age: 19


# Executes because both exist
if alex?.name?
  console.log alex.name


# Doesn't execute because alex.job
# is null
if alex?.job?
  console.log alex.job


# Doesn't execute because method doesn't
# exist
alex.someOtherMethod?()


# Doesn't execute because peter is null
if peter?.job?
  console.log peter.job
  • Check if a variable or property is null

  • Check if a method exists

  • "Soaking"

Other Syntax Helpers

# Inline "if" statements

homeworkComplete = false
submitTheHomework() if homeworkComplete

# Multi-Line Strings

theString = """
  This is my string that spans many lines.
  It will preserve newlines and stuff and escape
  characters where needed.
  """

# Cleaner switch statements

score = 76
grade = switch
  when score < 60 then 'F'
  when score < 70 then 'D'
  when score < 80 then 'C'
  when score < 90 then 'B'
  else 'A'

# Comparisons in plain English

a = 39
return true if a is 39
return false if a is not 39

switch = true
turnOnTheLights() if switch is on

Other things to Know

  • CoffeeScript is just JavaScript -- any libraries for JavaScript can be used in CoffeeScript, and many JavaScript generators support CoffeeScript
  • Doesn't solve all of JavaScript's problems
  • Requires a build step, but that doesn't matter

Resources

Intro to CoffeeScript

By Alex LaFroscia

Intro to CoffeeScript

A basic introduction to some of the useful bits of CoffeeScript, a useful language that compiles to JavaScript

  • 1,460