This week I’ve spent some time researching different CoffeeScript resources to be used for training at a client. In the process I’ve discover a few CoffeeScript features that I didn’t know about or are not that well known.
You probably know the standard way of iterating through a list in CoffeeScript.
But did you know that by passing an extra argument, you can also get the current iteration index?
But did you know that CoffeeScript supports splatting?
CoffeeScript also supports comprehensions – a little bit like the map function in Ruby.
Destructuring Assignment is just a fancy way of saying we can assign multiple variables at once. You can use it to switch the value of two variables in a single line.
You can also use this to assign variables to the result of a function.
It even works with deeply nested objects!
Destructuring Assignment combined with Splatting
Destructuring Assignment also works when combined with Splatting, which gives you another powerful way of dealing with arrays of variable length.
CoffeeScript also allows us to do Chained Comparisons (borrowed from Python) – which allows us to easily test if a value fall within a certain range.
You probably know that CoffeeScript supports string interpolation (using the same syntax as Ruby).
You probably know that @ is the shorthand for accessing this in CoffeeScript. But did you know that CoffeeScript has a similar shorthand for accessing the prototype of a class?
Binding Parameters to Properties
CoffeeScript allows us to bind parameters to properties directly by using the @ shorthand. For example, you often want to set properties in the constructor.
But we can just bind this property in the function declaration. CoffeeScript is the only language that I know of that allows you to do this.
The @ shorthand also allows us to define class functions.
My random implementation is a reference to XKCD.