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
If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.
Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.
Sponsored by ActiveState
Web Development News
Developer Poll
| Speed Up Your Web Site with Varnish | Jun 19, 2013 |
| Non-Linux FOSS: libnotify, OS X Style | Jun 18, 2013 |
| Containers—Not Virtual Machines—Are the Future Cloud | Jun 17, 2013 |
| Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer | Jun 12, 2013 |
| Weechat, Irssi's Little Brother | Jun 11, 2013 |
| One Tail Just Isn't Enough | Jun 07, 2013 |
- Speed Up Your Web Site with Varnish
- Containers—Not Virtual Machines—Are the Future Cloud
- Linux Systems Administrator
- Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer
- Non-Linux FOSS: libnotify, OS X Style
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- RSS Feeds
- Reply to comment | Linux Journal
10 min 40 sec ago - Reply to comment | Linux Journal
4 hours 10 min ago - Yeah, user namespaces are
5 hours 26 min ago - Cari Uang
8 hours 57 min ago - user namespaces
11 hours 51 min ago - yea
12 hours 17 min ago - One advantage with VMs
14 hours 45 min ago - about info
15 hours 19 min ago - info
15 hours 20 min ago - info
15 hours 20 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.