CoffeeScript in a Nutshell, Part 2: CoffeeScript Language Basics
This article is Part 2 of a four-part series on CoffeeScript. Part 1 introduced you to the CoffeeScript language and summarized its advantages over JavaScript. It also showed you how to obtain and use the core and command-line CoffeeScript compilers. This article continues the series by exploring basic CoffeeScript language features. You can download the code from this article here.
Comments
Comments document source code. CoffeeScript supports two kinds of comments: single-line and block. A single-line comment begins with a single hash character (#) and continues to the end of the current line, as the following example demonstrates:
# Simple Interest = Principal * Rate * Term
In contrast, a block comment begins and ends with three hash characters (###) and can span multiple lines. The following example presents a pair of block comments:
### It's customary to place text between lines that start with the three hashes. ### ### However, you can also place text on the same line as the three hashes. ###
The CoffeeScript compiler doesn't pass single-line comments to JavaScript; they don't appear in JavaScript code. However, it passes block comments. For example, if you were to compile the previous single-line and block comment examples, you would see the following JavaScript code:
/* It's customary to place text between lines that start with the three hashes. */ /* However, you can also place text on the same line as the three hashes. */
Semicolons and Significant Whitespace
CoffeeScript's compiler automatically inserts semicolons into generated JavaScript code. However, you still have to insert semicolons between standalone code items on the same line. The following example demonstrates this exception:
console.log "Hello,"; console.log "World"
This example outputs Hello, on one line and World on the line immediately below.
The equivalent JavaScript code is as follows:
console.log("Hello,"); console.log("World");
CoffeeScript handles most semicolons on your behalf to address a problem with the JavaScript parser. The parser inserts missing semicolons, but occasionally makes mistakes.
CoffeeScript uses significant whitespace (whitespace that has meaning within source code) instead of braces ({ }) to identify blocks of code. Each line belonging to a block is indented by the same amount of whitespace:
if x > y x = y console.log "x is now equal to y"
The same indentation for each of x = y and console.log "x is now equal to y" indicates that these lines belong to a block of code that's executed when x contains a value greater than the value of y. The equivalent JavaScript code appears below:
if (x > y) { x = y; console.log("x is now equal to y"); }
You must be careful when indenting each line in a block. Consider the following example:
if x > y x = y console.log "x is now equal to y"
Except for the extra space in front of x = y, this example's CoffeeScript code is identical to the earlier CoffeeScript example. However, the equivalent JavaScript code reveals a larger difference:
if (x > y) { x = y; } console.log("x is now equal to y");
The extra space made CoffeeScript interpret x = y as the only line of code belonging to the block following if x > y. The console.log "x is now equal to y" line is moved out of the block and is always executed.
Improper indentation can lead to compiler errors, which I demonstrate below:
if x > y x = y
Without indentation, the compiler doesn't find a block following if x > y. Instead, it sees x = y as independent code that executes regardless of the value of x > y and generates an error message.
You also must be careful with significant whitespace in other contexts, such as when adding two variables to produce a sum. Consider the following examples:
x = a + b x = a+b x = a+ b x = a +b
CoffeeScript interprets the first three x = ... lines as adding a and b. However, it interprets the fourth line as invoking function a with +b as an argument. This is borne out by the following JavaScript equivalent:
x = a + b; x = a + b; x = a + b; x = a(+b);
CoffeeScript interprets the fourth line as a function call because you don't have to supply parentheses when invoking a function that takes arguments. Instead, you can surround arguments with whitespace. We'll consider this capability in more detail later in this article.
Variables
JavaScript distinguishes between global variables and local variables:
- Global variables are defined in global scope (outside any function) with/without the keyword var, or in local scope (inside a function) without var.
- Local variables are defined in local scope with var.
Accidentally creating global variables can lead to name conflicts with other same-named globals, often resulting in hard-to-find bugs. CoffeeScript solves this problem by reserving var (you get a syntax error when using it) and implicitly creating local variables.
Behind the scenes, the compiler declares variables via var at the top of their functions, ensuring that these variables are local to them (preventing you from polluting the global namespace), and initializes them later in the functions. Consider the following example:
PI = 3.14159
CoffeeScript's compiler converts this script into the following JavaScript:
(function() { var PI; PI = 3.14159; }).call(this);
In this example, PI is declared at the beginning of the top-level function safety wrapper (discussed in Part 1). It's subsequently initialized later in the function.
You can still have global variables, but you must add them as properties of a global object, such as window in a browser context or exports in a Node.js context.
String Interpolation, Multiline Strings, and Block Strings
CoffeeScript supports Ruby-style string interpolation, in which #{varname} placeholders (varname signifying a variable name) are inserted into doubly-quoted string literals. The compiler replaces each placeholder with the value of its variable. Consider the following example:
name = "John" greeting = "Hello #{name}" # CoffeeScript assigns "Hello John" (without the " # characters) to greeting.
The JavaScript equivalent of this example reveals simple string concatenation:
name = "John"; greeting = "Hello " + name;
You can mix different types of variables in the same string literal to create more sophisticated templates. The following example combines the previous string variable name with number variable amount and literal text into a template for outputting checking account balances:
amount = 100.0 balance = "#{name}'s checking account contains #{amount} dollars."
The JavaScript equivalent appears below:
amount = 100.0; balance = "" + name + "'s checking account contains " + amount + " dollars.";
Some templates might be too long to fit on a line. To address this problem, CoffeeScript lets you split a string literal over multiple lines. The resulting multiline string is demonstrated below:
mgr = "Dave" msg = "Dear #{name}, Thank you for evaluating our product. We are confident that it will meet your needs. Sincerely, #{mgr}"
The JavaScript equivalent (split across two lines for readability) appears below:
mgr = "Dave"; msg = "Dear " + name + ", Thank you for evaluating our product. We are confident that it will meet your needs. Sincerely, " + mgr;
If you viewed the previous multiline string in your browser's JavaScript alert dialog box, the result wouldn't look nicely formatted. Fortunately, CoffeeScript goes a step further by supporting block strings—string literals that support nicely formatted multiline text.
A block string begins with ''' or """, can flow over multiple lines, respects indentation, supports string interpolation (double quotes only), and ends with ''' or """. The following example changes the previous example into a block string:
msg2 = """ Dear #{name}, Thank you for evaluating our product. We are confident that it will meet your needs. Sincerely, #{mgr} """
Viewing the resulting string in your browser's JavaScript alert dialog box shows that the formatting has been respected. The following JavaScript code (split across two lines for readability) reveals inserted newline character escapes (\n), which account for the formatting:
msg2 = "Dear " + name + ",\nThank you for evaluating our product. We are confident that it will meet your\nneeds.\nSincerely,\n" + mgr;
Object Literals
Object literals are objects expressed as collections of properties, where a property is a combination of a name and a value. The following example presents an account1 object literal:
account1 = { type: "savings", balance: 20000 } console.log account1.type # output: savings console.log account1.balance # output: 20000
The compiler translates this example into the following JavaScript equivalent:
account1 = { type: "savings", balance: 20000 }; console.log(account1.type); console.log(account1.balance);
Although the previous example is valid CoffeeScript code, CoffeeScript lets you simplify the object literal by eliminating the braces and the comma, which the following example demonstrates:
account2 = type: "checking" balance: 800 console.log account2.type # output: checking console.log account2.balance # output: 800
Apart from account2 instead of account1 and different property values, the equivalent JavaScript code is identical to the previous JavaScript code.
Arrays and Ranges
JavaScript's Array object denotes an array. Its property names are integer indexes, and it has a special length property whose nonnegative value denotes the array's length (number of integer-named properties).
In JavaScript and CoffeeScript, you can create an array by instantiating Array. Alternatively, you can use syntactic sugar to create this array; for example, [1, "dog", true]—array elements can have different types.
In CoffeeScript, commas are optional when array elements are placed on their own lines. This capability is demonstrated in the following example:
directions = [ "north" "south" "east" "west" ] console.log directions[1] # output: south
Here's the equivalent JavaScript code:
directions = ["north", "south", "east", "west"]; console.log(directions[1]);
A companion to the array is the range, which is a bounded sequence of values. You can create an inclusive sequence by placing two dots between the first and last values, and an exclusive sequence in which the last value isn't included by placing three dots between these values:
[1..10] # a sequence of integers from 1 through 10 [1...10] # a sequence of integers from 1 through 9
Ranges typically involve integer first/last values, as demonstrated above. However, they could be character values (for example, ['a'..'z']) or even variables (such as [a...b]).
Ranges are often used to extract portions of arrays, an activity known as slicing. For example, the following CoffeeScript code fragment returns a two-element array whose first element is "mon" and whose second element is "tue":
console.log ["mon", "tue", "wed", "thu", "fri", "sat", "sun"][0...2]
The JavaScript equivalent appears below:
console.log(["mon", "tue", "wed", "thu", "fri", "sat", "sun"].slice(0, 2));
Ranges also are often used to replace portions of arrays, an activity known as splicing. For example, the following CoffeeScript code fragment changes the first two elements in a seven-element array of shortened versions of weekday names:
weekdays = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] weekdays[0...2] = ["Monday", "Tuesday"] console.log weekdays
The JavaScript equivalent appears below:
weekdays = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]; [].splice.apply(weekdays, [0, 2].concat(_ref = ["Monday", "Tuesday"])), _ref; console.log(weekdays);
Ranges are typically specified in ascending order ([1..10]), but they can be specified in descending order ([10..1]). Also, when you assign a range to a variable, CoffeeScript converts the range into an array (for instance, [1..3] becomes [1, 2, 3]).
Functions
CoffeeScript provides several features that facilitate defining and working with functions. To define a function, specify an optional parameter list, followed by an arrow (->), followed by the function body. The following examples demonstrate function definition:
-> answerToLife = -> 42 rnd = (x) -> x * Math.random() | 0 # | 0 removes fractional part
The first example defines the empty function, the second example defines a function without a parameter list and which returns the integer 42, and the third example defines a function that takes one parameter and returns a random integer from 0 through one less than the parameter value.
The equivalent JavaScript code appears below:
(function() {}); answerToLife = function() { return 42; }; rnd = function(x) { return x * Math.random() | 0; };
The second and third examples show that you don't have to specify return to return a value, although you can do so if desired. CoffeeScript's compiler inserts this keyword on your behalf.
In the absence of a parameter list, you must specify parentheses after the function name when calling the function. However, when a parameter list is present, you often don't have to specify the parentheses. Consider the following examples:
console.log answerToLife() console.log rnd 100
If you fail to specify the parentheses for answerToLife, a Function object is returned instead of this function being called.
Sometimes it's necessary to surround parameter lists with parentheses in order to avoid errors. For example, consider the following JavaScript example:
document.getElementsByTagName("body")[0].appendChild(canvas);
You might consider expressing this example in CoffeeScript, as follows:
document.getElementsByTagName "body"[0].appendChild canvas
However, the CoffeeScript compiler converts this CoffeeScript code into the following JavaScript code:
document.getElementsByTagName("body"[0].appendChild(canvas));
The "body"[0].appendChild portion of this code is erroneous—appendChild is not a member of the String type. To correct this problem, you must surround "body" with parentheses, as follows:
document.getElementsByTagName("body")[0].appendChild canvas
Default Arguments
You can assign default arguments to parameters; specify = followed by a suitable value after the parameter name. Consider the following example:
report = (name, mgr = "Jeff Friesen") -> """ Dear #{name}, Thank you for evaluating our product. We are confident that it will meet your needs. Sincerely, #{mgr} """ console.log report "Jane Doe" console.log report "Jane Doe", "John Smith"
This example creates a report function with a parameter list consisting of name and mgr parameters. It then invokes this function twice, passing "Jane Doe" to name on each invocation.
The first invocation doesn't specify an argument for the second parameter, which then defaults to Jeff Friesen. The second invocation passes "John Smith" to mgr.
The JavaScript equivalent (split across two lines for readability) follows:
report = function(name, mgr) { if (mgr == null) { mgr = "Jeff Friesen"; } return "Dear " + name + ",\nThank you for evaluating our product. We are confident that it will meet your\nneeds.\nSincerely,\n" + mgr; }; console.log(report("Jane Doe")); console.log(report("Jane Doe", "John Smith"));
Splats
Another function feature is splats, which let you pass a variable number of arguments to a function. A splat is indicated by the presence of an ellipsis (...) immediately following the rightmost parameter name, as demonstrated below:
avg = (numbers...) -> sum = 0; for i in [0...numbers.length] sum += numbers[i] sum/numbers.length console.log avg 1, 2, 3, 4, 5, 6
This example introduces a function that computes the average of a numeric array. It uses a for loop (discussed in Part 3) to iterate over this array and update a sum. Finally, the function returns the sum divided by the numeric array's length.
The JavaScript equivalent (slightly modified for readability) appears below:
avg = function() { var i, numbers, sum, _i, _ref1; numbers = 1 <= arguments.length ? __slice.call(arguments, 0) : []; sum = 0; for (i = _i = 0, _ref1 = numbers.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; i = 0 <= _ref1 ? ++_i : --_i) { sum += numbers[i]; } return sum / numbers.length; }; console.log(avg(1, 2, 3, 4, 5, 6));
Conclusion
This article introduced you to CoffeeScript's basic language features. You learned about comments; semicolons and significant whitespace; variables; string interpolation, multiline strings, and block strings; object literals; arrays and ranges; and functions. Part 3 explores CoffeeScript's expression-oriented features.