CoffeeScript Techniques

List Comprehensions

Very Python-y technique I use on a daily basis:

for k,v of myList
    console.log('%s has %s', key, value)

How to pop an element in Coffeescript?

While in Python this would be easy, how to achieve in Coffeescript, e.g.

leet = [1,3,3,7]
leet.pop(-1)
leet.pop(-1)

.pop() method

leet = [1,3,3,7]
leet.pop() # returns 7 and leet will become 1,3,3
leet.pop() # returns 3 and leet will become 1,3

Try it out: http://codepen.io/nottinhill/pen/oXvxrQ

Check for undefined

CoffeeScript

bookInShelf += inventoryCounter if bookInShelf?

Compiled JS

if (typeof bookInShelf !== "undefined" && bookInShelf !== null) {
    bookInShelf += inventoryCounter;
}

Check for Number Type

CoffeeScript

isFinite n

Compiled JS

isFinite (n);

Or even better, use lodash utility functions, like

._isFinite n

or

._isNumber n

https://lodash.com/docs#isFinite
https://lodash.com/docs#isNumber