Arrays

CoffeeScript takes inspiration from Ruby when it comes to array slicing by using ranges. Ranges are created by two numerical values, the first and last positions in the range, separated by .. or .... If a range isn’t prefixed by anything, CoffeeScript expands it out into an array:

range = [1..5]

If, however, the range is specified immediately after a variable, CoffeeScript converts it into a slice() method call:

firstTwo = ["one", "two", "three"][0..1]

In the example above, the range returns a new array, containing only the first two elements of the original array. You can also use the same syntax for replacing an array segment with another array:

numbers = [0..9]
numbers[3..5] = [-3, -4, -5]

What’s neat, is that JavaScript allows you to call slice() on strings too, so you can use ranges with string to return a new subset of characters:

my = "my string"[0..1]

Checking to see if a value exists inside an array is always a bore in JavaScript, particularly because indexOf() doesn’t yet have full cross-browser support (Internet Explorer, I’m talking about you). CoffeeScript solves this with the in operator, for example:

words = ["rattled", "roudy", "rebbles", "ranks"]
alert "Stop wagging me" if "ranks" in words

Get The Little Book on CoffeeScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.