Home > Articles > Open Source > Ajax & JavaScript

CoffeeScript in a Nutshell, Part 2: CoffeeScript Language Basics

CoffeeScript presents basic language features that you must understand before diving into advanced language features. In Part 2 of this four-part series, Jeff Friesen introduces the basic features: comments; semicolons and significant whitespace; variables; string interpolation, multiline strings, and block strings; object literals; arrays and ranges; and functions.
Like this article? We recommend

Like this article? We recommend

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020