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
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
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
| 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 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- New Products
- RSS Feeds
- Tech Tip: Really Simple HTTP Server with Python
- Epistle
1 hour 1 min ago - Automatically updating Guest Additions
2 hours 9 min ago - I like your topic on android
2 hours 56 min ago - Reply to comment | Linux Journal
3 hours 17 min ago - This is the easiest tutorial
9 hours 31 min ago - Ahh, the Koolaid.
15 hours 10 min ago - git-annex assistant
21 hours 10 min ago - direct cable connection
21 hours 32 min ago - Agreed on AirDroid. With my
21 hours 42 min ago - I just learned this
21 hours 47 min 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.