---
title: "CoffeeScript Tricks"
summary: "Four CoffeeScript tricks which aren't in the docs."
date: 2013-11-25
authors: [zack-bloom]
topics: [Frontend]
canonical: https://product.hubspot.com/blog/coffeescript-tricks
cover:
  scene: coffeescript-tricks
  alt: "A sausage dog trots out of a tiny kennel and its body keeps coming, along the fence and back across the lawn; the ball its owner tosses bonks off its nose and lies on the grass."
---

At HubSpot, I'm fortunate to work with some CoffeeScript [experts](http://pragprog.com/book/tbcoffee/coffeescript).  I've picked up a few tricks, most of which aren't mentioned in the [docs](http://coffeescript.org/).

## Try Without Catch

One of my first confusions with CoffeeScript was why it always required you to assign the 'catched' error to something, you couldn't have a catch and just drop the error object on the floor. Turns out you can do one better:

<CodeTabs>

```coffeescript title="CoffeeScript"
try
  thisMightThrowAnError()

butThisDoesntCare()
```

```javascript title="Compiled JavaScript"
try {
  thisMightThrowAnError();
} catch (_error) {}

butThisDoesntCare();
```

</CodeTabs>

## Destructuring Arguments

It's common in CoffeeScript, as in Javascript, to pass objects as options to methods. This get's even easier when you use destructing assignment. This is a great way to get the clean binding of positional arguments while maintaining the flexibility of an object.

<CodeTabs>

```coffeescript title="CoffeeScript"
myMethod = ({size, weight}) ->
  @cost = size * weight
```

```javascript title="Compiled JavaScript"
myMethod = function(_arg) {
  var size, weight;
  size = _arg.size, weight = _arg.weight;
  return this.cost = size * weight;
};
```

</CodeTabs>

You can couple that with the 'this' shorthand:

<CodeTabs>

```coffeescript title="CoffeeScript"
class Ball
  constructor: ({@size}) ->
```

```javascript title="Compiled JavaScript"
Ball = (function() {
  function Ball(_arg) {
    this.size = _arg.size;
  }
  return Ball;
})();
```

</CodeTabs>

It gets even better when you use the object shorthand notation:

<CodeTabs>

```coffeescript title="CoffeeScript"
size = 55
new Ball {size}
```

```javascript title="Compiled JavaScript"
size = 55;
new Ball({
  size: size
});
```

</CodeTabs>

The shorthand style is particularly nice when it comes time for you to define `module.exports`:

<CodeTabs>

```coffeescript title="CoffeeScript"
module.exports = {start, stop}
```

```javascript title="Compiled JavaScript"
module.exports = {
  start: start,
  stop: stop
};
```

</CodeTabs>

You can even use the shorthand with object properties:

<CodeTabs>

```coffeescript title="CoffeeScript"
return {@id}
```

```javascript title="Compiled JavaScript"
return {id: this.id}
```

</CodeTabs>

## Static Methods

In Javascript, functions are objects, and classes are just functions, meaning you can attach static methods to your classes:

```coffeescript
class MyModel

MyModel.get = _.memoize ->
  new MyModel
```

It turns out that CoffeeScript has a syntax for just this situation:

<CodeTabs>

```coffeescript title="CoffeeScript"
class MyModel
  @get: _.memoize ->
    new MyModel
```

```javascript title="Compiled JavaScript"
MyModel = (function() {
  function MyModel() {}
  MyModel.get = _.memoize(function() {
    return new MyModel;
  });
  return MyModel;
})();
```

</CodeTabs>

## Anonymous Functions

One of the classic bugs folks encounter in Javascript is forgetting that only functions have scope, so anything assigned in a for loop, for example, may have changed when it comes time for callbacks to fire. The `do` keyword can be used to call a function immediately, passing it it's arguments from the outer scope.

<CodeTabs>

```coffeescript title="CoffeeScript"
for dog in dogs
  do (dog) ->
    setTimeout ->
      console.log "Dog:", dog
```

```javascript title="Compiled JavaScript"
_fn = function(dog) {
  return setTimeout(function() {
    return console.log("Dog:", dog);
  });
};
for (_i = 0, _len = dogs.length; _i < _len; _i++) {
  dog = dogs[_i];
  _fn(dog);
}
```

</CodeTabs>

You can use the default argument value to create variables which will only live in the inner scope.

<CodeTabs>

```coffeescript title="CoffeeScript"
do (x=3) -> letsRock(x)
```

```javascript title="Compiled JavaScript"
(function(x) {
  return letsRock(x);
})(3);
```

</CodeTabs>

You can also use this trick to call functions as you create them:

<CodeTabs>

```coffeescript title="CoffeeScript"
do check = ->
  if waitingOn is 0
   done()

setTimeout check, 50
```

```javascript title="Compiled JavaScript"
(check = function() {
  if (waitingOn === 0) {
    return done();
  }
})();
setTimeout(check, 50);
```

</CodeTabs>

## Reverse Iteration

Since CoffeeScript 1.5.0 it's been possible to iterate through a list in reverse:

<CodeTabs>

```coffeescript title="CoffeeScript"
for car in cars by -1
  start(car)
```

```javascript title="Compiled JavaScript"
for (_i = cars.length - 1; _i >= 0; _i += -1) {
  car = cars[_i];
  start(car);
}
```

</CodeTabs>

## Splats

Most CoffeeScript developers know about splats, but not all know that they can appear anywhere in the argument sequence.

<CodeTabs>

```coffeescript title="CoffeeScript"
(name, children..., cb) ->
```

```javascript title="Compiled JavaScript"
var __slice = [].slice;
(function() {
  var cb, children, name, _i;
  name = arguments[0], children = 3 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 1) : (_i = 1, []), cb = arguments[_i++];
});
```

</CodeTabs>

For one of our favorite CoffeeScript tricks, take a look at [Mixen](http://github.hubspot.com/mixen).
