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 very much like the code we might write by hand to do this if we weren't lucky enough to be using CoffeeScript.
You might choose to use this syntax simply for convenience when initializing some values:
[login, password] = ["admin", "r00tsh3ll"]
Or you...