String Interpolation
Anyone who writes a lot of JavaScript is very familiar with the way of building strings.
var verb = "mash"; var operators = "plus symbols"; "You " + verb + " them " together using " + operators + "."
This style leaves a little to be desired. One flaw is that it overloads the +
operator, and leads to subtle bugs when combining strings and integers. It's easy to overlook the fact that 1 + 2 + "3"
will behave differently than "3" + 2 + 1
. The other flaw with building strings in JavaScript is that it quickly becomes difficult to read. You find yourself spending time corralling spaces and quote marks just to make sure your string turns out like you are expecting. It's especially painful anytime you find yourself constructing HTML strings by hand and wish to insert dynamic attributes. Let's not even mention the trouble you can get into mixing '
and "
characters!
Thankfully, CoffeeScript has a better solution for building strings. Use #{}
inside a double-quoted string to surround...