10 CoffeeScript Features You Might Not Know
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.
Iterations
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?
Splatting
JavaScript (and therefore CoffeeScript) doesn’t enforce that you pass the correct number of parameters to a function. In this example the last few parameters will just get dropped.
But did you know that CoffeeScript supports splatting?
Comprehensions
CoffeeScript also supports comprehensions – a little bit like the map function in Ruby.
Destructuring Assignment
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.
Chained Comparisons
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.
Block Strings
You probably know that CoffeeScript supports string interpolation (using the same syntax as Ruby).
But did you know that JavaScript supports block strings? This is very useful for formatted or indentation-sensitive text. The indentation level that begins the block is maintained throughout, so you can keep it all aligned with the body of your code.
Prototype Shorthand
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.
Class/Static Functions
The @ shorthand also allows us to define class functions.
My random implementation is a reference to XKCD.
Happy coding.