Jump to content

CoffeeScript: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
m update
Line 27: Line 27:


== Syntax ==
== Syntax ==
Almost everything is an expression in CoffeeScript, for example <code>if</code>, <code>switch</code> and <code>for</code> expressions (which have no return value in JavaScript) return a value. As in [[Perl]], these control statements also have postfix versions; for example, <code>if</code> can also be written after the conditional statement.
Almost everything is an expression in CoffeeScript, for example <code>if</code>, <code>switch</code> and <code>for</code> expressions (which have no return value in JavaScript) return a value. As in [[Perl]], these control statements also have posix versions; for example, <code>if</code> can also be written after the conditional statement.


Many unnecessary parentheses and braces can be omitted; for example, blocks of code can be denoted by indentation instead of braces, function calls are implicit, and object literals are often detected automatically.
Many unnecessary parentheses and braces can be omitted; for example, blocks of code can be denoted by indentation instead of braces, function calls are implicit, and object literals are often detected automatically.

Revision as of 15:50, 18 September 2014

CoffeeScript
File:CoffeeScript-logo.png
ParadigmMulti-paradigm: prototype-based, functional, imperative, scripting
Designed byJeremy Ashkenas
DeveloperJeremy Ashkenas, et al.
First appearedDecember 13, 2009; 15 years ago (2009-12-13)
Stable release
1.8.0 / August 26, 2014; 10 years ago (2014-08-26)
OSCross-platform
LicenseMIT License
Filename extensions.coffee
Websitecoffeescript.org
Influenced by
Haskell,[1] JavaScript, Perl, Python,[1] Ruby,[1] YAML[2]
Influenced
MoonScript, LiveScript

CoffeeScript is a programming language that transcompiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python and Haskell[1] to enhance JavaScript's brevity and readability.[citation needed] Specific additional features include list comprehension and pattern matching.

The language has a relatively large following[citation needed] in the Ruby community. CoffeeScript support is included in Ruby on Rails version 3.1.[3] In 2011, Brendan Eich referenced CoffeeScript as an influence on his thoughts about the future of JavaScript.[4][5]

History

On December 13, 2009, Jeremy Ashkenas made the first Git commit of CoffeeScript with the comment: "initial commit of the mystery language."[6] The compiler was written in Ruby. On December 24, he made the first tagged and documented release, 0.1.0. On February 21, 2010, he committed version 0.5, which replaced the Ruby compiler with a self-hosting version in pure CoffeeScript. By that time the project had attracted several other contributors on GitHub, and was receiving over 300 page hits per day.

On December 24, 2010, Ashkenas announced the release of stable 1.0.0 to Hacker News, the site where the project was announced for the first time.[7][8]

Syntax

Almost everything is an expression in CoffeeScript, for example if, switch and for expressions (which have no return value in JavaScript) return a value. As in Perl, these control statements also have posix versions; for example, if can also be written after the conditional statement.

Many unnecessary parentheses and braces can be omitted; for example, blocks of code can be denoted by indentation instead of braces, function calls are implicit, and object literals are often detected automatically.

Examples

Interval test

To compute the body mass index, one may do (here in JavaScript):

var mass = 72
var height = 1.78
var BMI = mass / height / height
if (18.5 < BMI && BMI < 25) alert('You are healthy!')

With CoffeeScript the interval is directly described:

mass = 72
height = 1.78
BMI = mass / height**2
alert 'You are healthy!' if 18.5 < BMI < 25

Loops and comprehensions

To compute the greatest common divisor of two integer numbers with the euclidean algorithm, one usually needs a while loop:

function gcd(x, y) {
  var z
  do {
    z = x % y
    x = y
    y = z
  } while (y != 0)
  return x
}

Whereas in CoffeeScript one can use until and pattern-matching instead:

gcd = (x, y) ->
  [x, y] = [y, x%y] until y is 0
  x

Any for loop can be replaced by a list comprehension; so that to compute the squares of the positive odd numbers smaller than ten (i.e. numbers which remainder modulo 2 is 1), one can do

alert n*n for n in [1..10] when n%2 is 1

Alternatively, there is

alert n*n for n in [1..10] by 2

Functions and jQuery

A common JavaScript snippet using the jQuery library is

$(document).ready(function() {
  // Initialization code goes here
})

Or even just

$(function() {
  // Initialization code goes here
})

In CoffeeScript, the function keyword is replaced by the -> symbol, and indentation is used instead of curly braces, as in other off-side rule languages such as Python and Haskell. Also, parentheses can usually be omitted. Thus, the CoffeeScript equivalent of the snippet above is

$(document).ready ->
  # Initialization code goes here

Or just

$ ->
  # Initialization code goes here

String Interpolation

Ruby-style string interpolation is included in CoffeeScript. Double-quoted strings allow for interpolated values, using #{ ... }, and single-quoted strings are literal.[9]

author = "Wittgenstein"
quote  = "A picture is a fact. -- #{ author }"

sentence = "#{ 22 / 7 } is a decent approximation of π"

Dynamic Variables in a Class

It might not appear to be useful at first glance, but there are times where using this technique is useful. It allows you to create variables in a class, with dynamic names.

class DynamicVariables
  constructor: (variables) ->

    for variable in variables 
      do (variable) =>
        @[variable] = "Default value for #{variable}" #attach a variable to the class

baz = new DynamicVariables ['foo', 'bar']

console.log baz.foo
# > Default value for foo

Compiling

The CoffeeScript compiler has been written in CoffeeScript since version 0.5 and is available as a Node.js utility; however, the core compiler does not rely on Node.js and can be run in any JavaScript environment.[10] One alternative to the Node.js utility is the Coffee Maven Plugin, a plugin for the popular Apache Maven build system. The plugin uses the Rhino JavaScript engine written in Java.

The official site at CoffeeScript.org has a "Try CoffeeScript" button in the menu bar; clicking it opens a modal window in which users can enter CoffeeScript, see the JavaScript output, and run it directly in the browser. The js2coffee[11] site provides bi-directional translation.

Issues

  • CoffeeScript is very sensitive to whitespace, counting a tab as a single space.
  • The compiler provides very rudimentary diagnostic information in the case of errors.
  • Priority rules are not always intuitive, sometimes causing sub-expressions to end up in unexpected places.
  • Debugging is a major problem because the compiled code is not always readable.
  • Claim of increased source code readability can be disputed.

The above issues are only indicative and there are many other strong arguments for and against CoffeeScript.[12]

Latest additions

  • Source maps offer a way to identify the corresponding JavaScript code while debugging CoffeeScript code.
  • CoffeeScript supports Literate Programming where one could use .litcoffee file extensions to write readable programs.

Adoption

On September 13, 2012, Dropbox announced that their browser-side codebase has been rewritten from JavaScript to CoffeeScript.[13] GitHub's internal style guide for their own code says to "write new JS in CoffeeScript".[14]

See also

References

  1. ^ a b c d The Changelog. Episode 0.2.9 - CoffeeScript with Jeremy Ashkenas, July 23, 2010
  2. ^ Heller, Martin (18 October 2011). "up your nose at Dart and smell the CoffeeScript". JavaWorld. InfoWorld. Retrieved 2012-02-09.
  3. ^ , Joshua. Tweet by Rails Core Team Member on Apr 13, 2011
  4. ^ Eich, Brendan. "Harmony of My Dreams"
  5. ^ Eich, Brendan. "My JSConf.US Presentation"
  6. ^ Github. 'initial commit of the mystery language'
  7. ^ Hacker News. CoffeeScript 1.0.0 announcement posted by Jeremy Ashkenas on Dec 24, 2010
  8. ^ Hacker News. Original CoffeeScript announcement posted by Jeremy Ashkenas on Dec 24, 2009
  9. ^ "Official CoffeeScript Page". Retrieved 20 November 2013.
  10. ^ CoffeeScript. Jashkenas.github.com. Retrieved on 2013-07-21.
  11. ^ Sta Cruz, Rico. "js2coffee.org". Retrieved 11 May 2014.
  12. ^ Way, Jeffrey (14 Dec 2011). "Should you learn CoffeeScript". tuts+. Retrieved 11 May 2014.
  13. ^ Wheeler, Dan; Mahkovec, Ziga; Varenhorst, Chris (13 September 2012). "Dropbox dives into CoffeeScript". Retrieved 11 May 2013.
  14. ^ "JavaScript · Styleguide · GitHub". Github.com. Retrieved 2014-05-15.
  15. ^ "Rapydscript bitbucket repository". Atlassian Bitbucket. 3 Apr 2013. Retrieved 11 May 2014.

Further reading