Assigning multiple values at once

Let's look at a handy shorthand for assigning values to variables. CoffeeScript offers a feature called destructuring assignment . This is a fancy term that means you can assign multiple variables from an array or object using a single expression.

[first, second] = ["horse", "cart"]
console.log "Don't put the #{second} before the #{first}."

We were able to assign the variables first and second in one expression simply by adding square brackets around them. Looking at the compiled JavaScript shows us how CoffeeScript achieves this:

_ref = ["horse", "cart"], first = _ref[0], second = _ref[1];

It's using a temporary variable for reference, and then assigning the variables one at a time using array indexes. This looks ...

Get CoffeeScript Application Development 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.