Introducing CoffeeScript
Basic Syntax
To execute the function, just give the CoffeeScript REPL (read-eval-print loop) the name of the function, followed by parentheses (that is, execution):
coffee> hello_world()
CoffeeScript functions return their final value, much as Ruby methods do. In the case of this hello_world function, that means the function is returning "undefined". You can make that a bit better by having the function return the string, rather than print it:
coffee> hello_world = (name) -> "Hello there, #{name}!"
Then, you can say:
coffee> console.log hello_world('Reuven') Hello there, Reuven!
or:
coffee> hello_world('Reuven') 'Hello there, Reuven!'
depending on whether you want to get the string back or just print it to the console.
CoffeeScript provides the basic JavaScript data types, but it adds a great deal of syntactic sugar, as well as additional methods, that make those data types easier to deal with. For example, CoffeeScript uses Python-style triple-quoted strings.
The "existential" operator, a question mark (?), allows you to determine whether a variable contains something other than null or undefined values. This is better than just checking for the truth of a value, which will lead to (literal!) false negatives if a value contains 0 or the empty string. For example:
v = 0 if v console.log "yes" else console.log "no" if v? console.log "yes" else console.log "no"
The above code example shows how CoffeeScript implements if/else control blocks. There also is an "unless" operator, which (as you might expect) inverts the output from if. CoffeeScript also provides postfix "if" and "unless" statements—something you might recognize from Perl and Ruby.
You also can see another element of CoffeeScript above, this one taken from Python. Whitespace and indentation are significant, and allow you to remove much of the curly braces and begin/end of many other languages. Unlike Python, however, colons aren't necessary after the "if" and "else" statements.
CoffeeScript arrays are like JavaScript arrays, but with all sorts of nice syntax added. Want a ten-element array? Just use this:
a = [0..9]
and you'll get it, using the built-in "range" operator. (This doesn't work for letters though.) You can retrieve ranges as well:
a[5..7]
You can assign to a range, without worrying about the precise length of what you're splicing in:
a[5..7] = ['a', 'b']
You also can retrieve substrings using this syntax:
coffee> alphabet[5..10] alphabet[5..10] 'fghijk'
CoffeeScript strings, like JavaScript strings, are immutable. Thus, you cannot assign to a substring:
coffee> alphabet[5..10] = [5] alphabet[5..10] = [5] [ 5 ] coffee> alphabet alphabet 'abcdefghijklmnopqrstuvwxyz'
JavaScript objects, which can be used like hashes (aka "dictionaries" or "associative arrays") work just as they do in JavaScript, but with some easier syntax. For example, in JavaScript, you would write:
person = { first_name: 'Reuven', last_name: 'Lerner' }
In CoffeeScript, you can say:
person = first_name: 'Reuven' last_name: 'Lerner'
Once again, using Python-style indentation instead of curly braces makes it more compact but no less readable.
Loops and Comprehensions
You can loop through arrays with for..in:
for number in a console.log number
I should point out that this will print each number on a line by itself and will return an array of undefined values (because console.log doesn't return a value, and "for" returns an array).
Objects can be accessed using the similar for..of loop:
for key, value of person console.log "key = '#{value}'"
Note that for..of loops work on any JavaScript object. Because every object can contain properties, and because arrays are objects, you even can assign properties to arrays:
a.foo = 'bar'
Using a for..in loop, you'll continue to see the values in the "a" array. But using a for..of loop, you'll get not only the array elements (whose keys are the indexes), but also "foo". Additionally, note that if you're interested only in the properties defined on an object, rather than on its prototype, you can add the "own" keyword:
for own key, value of person console.log "key = '#{value}'"
In this particular case, there will be no difference. But if "person" were to have a prototype, and if the prototype were to have keys of its own, you would see the prototype's keys and values, and not just those for the "person" object.
But the need for these for..in and for..of loops is reduced dramatically in CoffeeScript because of comprehensions, an idea that comes from Python that takes some getting used to, but that offers a great deal of power and simplicity once you do so, allowing you to combine map, reduce and filter in a single statement. For example, you can take a list of numbers:
coffee> a = [100..110] [ 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110 ]
And you then can multiply each number by 5, much as you would do with "map" in Ruby or Python, but using "comprehension" syntax:
coffee> i*5 for i in a [ 500, 505, 510, 515, 520, 525, 530, 535, 540, 545, 550 ]
You also can select out some values. Suppose, for example, you want to operate only on those elements that are odd. You can say:
coffee> i*5 for i in a when i%2 [ 505, 515, 525, 535, 545 ]
Senior Columnist, Linux Journal
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
Web Development News
Developer Poll
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- Validate an E-Mail Address with PHP, the Right Way
- Build a Skype Server for Your Home Phone System
- Tech Tip: Really Simple HTTP Server with Python
- Why Python?
- A Topic for Discussion - Open Source Feature-Richness?
- Reply to comment | Linux Journal
15 min 36 sec ago - Not free anymore
4 hours 17 min ago - Great
8 hours 4 min ago - Reply to comment | Linux Journal
8 hours 12 min ago - Understanding the Linux Kernel
10 hours 27 min ago - General
12 hours 57 min ago - Kernel Problem
22 hours 59 min ago - BASH script to log IPs on public web server
1 day 3 hours ago - DynDNS
1 day 7 hours ago - Reply to comment | Linux Journal
1 day 7 hours ago







Comments
Javascript is still alive
Just goes to show that Javascript is still alive.I wonder how much memory it takes to compile from Coffee Script into Javascript.That might be a limiting factor in development.
The setup was confusing. How
The setup was confusing. How would you set this up for testing in a web browser?
Quite bad code formatting for
Quite bad code formatting for a whitespace-aware language.