Smooth CoffeeScript

Page 23

Basic CoffeeScript

There is one more arithmetic operator which is probably less familiar to you. The % symbol is used to represent the modulo operation. X modulo Y is the remainder of dividing X by Y. For example 314 % 100 is 14, 10 % 3 is 1, and 144 % 12 is 0. Modulo has the same precedence as multiplication and division. ◦•◦ The next data type is the string. Its use is not as evident from its name as with numbers, but it also fulfills a very basic role. Strings are used to represent text, the name supposedly derives from the fact that it strings together a bunch of characters. Strings are written by enclosing their content in quotes: 'Patch my boat with chewing gum.'

Almost anything can be put between quotes, and CoffeeScript will make a string value out of it. But a few characters are tricky. You can imagine how putting quotes between quotes might be hard. 'The programmer pondered: "0x2b or not 0x2b"'

CoffeeScript implements both single quoted and double quoted strings, which can be handy when you have only one kind of quote in a string. "Aha! It's 43 if I'm not a bit off"

Double quoted strings can contain interpolated values, small snippets of CoffeeScript code between #{ and }. The code is evaluated and inserted into the string. "2 + 2 gives #{2 + 2}"

Newlines, the things you get when you press enter, can not be put between quotes in the normal form of strings. A string can span multiple lines to help avoid overly long lines in the program but the line breaks are not shown in the output. 'Imagine if this was a very long line of text'

◦•◦ CoffeeScript has triple-quoted strings aka heredocs to make it easy to have strings that span multiple lines where the line breaks are preserved in the output. Indentation before the quotes are ignored so the following lines can be aligned nicely.

22


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.