CoffeeScriptis aprogramming languagethat compiles toJavaScript.It addssyntactic sugarinspired byRuby,Python,andHaskellin an effort to enhance JavaScript's brevity and readability.[4]Specific additional features includelist comprehensionanddestructuring assignment.
![]() | |
Paradigm | Multi-paradigm:prototype-based,functional,imperative,scripting |
---|---|
Designed by | Jeremy Ashkenas |
Developer | Jeremy Ashkenas |
First appeared | December 13, 2009 |
Stable release | 2.7.0[1] ![]() |
Typing discipline | dynamic,implicit |
OS | Cross-platform |
License | MIT License |
Filename extensions | .coffee ,.litcoffee [citation needed] |
Website | coffeescript |
Influenced by | |
Haskell,JavaScript,Perl,[citation needed]Python,[2]Ruby,YAML[3] | |
Influenced | |
MoonScript,LiveScript,JavaScript |
CoffeeScript support is included inRuby on Railsversion 3.1[5]andPlay Framework.[6]In 2011,Brendan Eichreferenced CoffeeScript as an influence on his thoughts about the future of JavaScript.[7][8]
History
editOn December 13, 2009,Jeremy Ashkenasmade the firstGitcommit of CoffeeScript with the comment "initial commit of the mystery language".[9]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 aself-hostingversion in pure CoffeeScript. By that time the project had attracted several other contributors onGitHub,and was receiving over 300 page hits per day.
On December 24, 2010, Ashkenas announced the release of stable 1.0.0 toHacker News,the site where the project was announced for the first time.[10][11]
On September 18, 2017, version 2.0.0 was introduced,[12]which "aims to bring CoffeeScript into the modern JavaScript era, closing gaps in compatibility with JavaScript while preserving the clean syntax that is CoffeeScript's hallmark".
Syntax
editAlmost everything is anexpressionin CoffeeScript, for example,if
,switch
andfor
expressions (which have no return value in JavaScript) return a value. As inPerland Ruby, these control statements also have postfix versions; for example,if
can also be written inconsequent if condition
form.
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.
To compute thebody mass indexinJavaScript,one could write:
letmass=72;
letheight=1.78;
letBMI=mass/height**2;
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!'if18.5<=BMI<25
To compute thegreatest common divisorof two integers with theEuclidean algorithm,in JavaScript one usually needs awhileloop:
letgcd=(x,y)=>{
do{
[x,y]=[y,x%y];
}while(y!==0)
returnx;
}
Whereas in CoffeeScript one can useuntil
[13]instead:
gcd=(x, y) ->
[x,y]=[y,x%y]untilyis0
x
The?
keyword quickly checks if a variable isnull
orundefined
:
personCheck=->
ifnotperson?thenalert("No person")elsealert("Have person")
person=null
personCheck()
person="Ivan"
personCheck()
This would alert "No person" if the variable isnull
orundefined
and "Have person" if there is something there.
A common pre-ES6JavaScript snippet using thejQuerylibrary is:
$(document).ready(function(){
// Initialization code goes here
});
Or even just:
$(function(){
// Initialization code goes here
});
In CoffeeScript, thefunction
keyword is replaced by the->
symbol, and indentation is used instead of curly braces, as in otheroff-side rulelanguages such as Python and Haskell. Also, parentheses can usually be omitted, using indentation level instead to denote a function or block. Thus, the CoffeeScript equivalent of the snippet above is:
$(document).ready->
# Initialization code goes here
Or just:
$->
# Initialization code goes here
Ruby-style string interpolation is included in CoffeeScript. Double-quoted strings allow for interpolated values, using #{... }, and single-quoted strings are literal.[14]
author="Wittgenstein"
quote="A picture is a fact. --#{author}"
sentence="#{22/7}is a decent approximation of π "
Anyforloopcan be replaced by alist comprehension;so that to compute the squares of the positive odd numbers smaller than ten (i.e. numbers whose remainder modulo 2 is 1), one can do:
alertn*nfornin[1..10]whenn%2is1
Alternatively, there is:
alertn*nfornin[1..10]by2
Alinear searchcan be implemented with a one-liner using the when keyword:
names=["Ivan","Joanna","Nikolay","Mihaela"]
linearSearch=(searchName) ->alert(name)fornameinnameswhennameissearchName
Thefor... in
syntax allows looping over arrays while thefor... of
syntax allows looping over objects.
CoffeeScript has been criticized for its unusualscopingrules.[15][16]In particular, it completely disallowsvariable shadowingwhich makes reasoning about code more difficult and error-prone in some basic programming patterns established by and taken for granted sinceprocedural programmingprinciples were defined.
For example, with the following code snippet in JavaScript
one does not have to look outside the{}
-block to know for
sure that no possiblefoo
variable in the outer scope can be
incidentally overridden:
//...
functionbaz(){
varfoo="bar";
console.log(`foo =${foo}`);
}
//...
}
In CoffeeScript there is no way to tell if the scope of a variable is limited to a block or not without looking outside the block.
Development and distribution
editThe CoffeeScript compiler has beenself-hostingsince version 0.5 and is available as aNode.jsutility; however, the core compiler does not rely on Node.js and can be run in anyJavaScriptenvironment.[17]One alternative to theNode.jsutility is the Coffee Maven Plugin, a plugin for theApache Mavenbuild system. The plugin uses theRhinoJavaScript engine written inJava.[citation needed]
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[18]site provides bi-directional translation.
Latest additions
edit- Source maps allow users to debug their CoffeeScript code directly, supporting CoffeeScript tracebacks on run time errors.
- CoffeeScript supports a form ofLiterate Programming,using the
.coffee.md
or.litcoffee
file extension. This allows CoffeeScript source code to be written inMarkdown.The compiler will treat any indented blocks (Markdown's way of indicating source code) as code, and ignore the rest as comments.
Extensions
editIced CoffeeScript is a superset of CoffeeScript which adds two new keywords:await
anddefer
.These additions simplify asynchronous control flow, making the code look more like aprocedural programminglanguage, eliminating the call-back chain. It can be used on the server side and in the browser.[19]
Adoption
editOn September 13, 2012,Dropboxannounced that their browser-side code base had been rewritten fromJavaScriptto CoffeeScript,[20]however it was migrated toTypeScriptin 2017.[21]
GitHub's internal style guide once said "write new JS in CoffeeScript", though it no longer does,[22]and theirAtom text editorwas also written in the language, with configuration written inCSON( "CoffeeScript Object Notation" ), a variant ofJSON.[23][24]
Pixel Game Maker MVmakes uses of CoffeeScript as part of its game development environment.[25]
See also
editReferences
edit- ^"2.7.0".24 April 2022.Retrieved9 August2022.
- ^https://coffeescript.org/"CoffeeScript borrows chained comparisons from Python"
- ^Heller, Martin (October 18, 2011)."Turn up your nose at Dart and smell the CoffeeScript".InfoWorld.Retrieved2020-07-15.
- ^Alex MacCaw (January 2012).The Little Book on CoffeeScript.O'Reilly Media.ISBN978-1-4493-2105-5.
- ^Josh Peek (April 13, 2011)."Tweet by Rails Core Team Member".
- ^"AssetsCoffeeScript - 2.5.x".www.playframework.com.Retrieved2016-10-31.
- ^Eich, Brendan. "Harmony of My Dreams"
- ^Eich, Brendan. "My JSConf.US Presentation"
- ^Github.'initial commit of the mystery language'
- ^Hacker News.CoffeeScript 1.0.0 announcementposted by Jeremy Ashkenas on Dec 24, 2010
- ^Hacker News.Original CoffeeScript announcementposted by Jeremy Ashkenas on Dec 24, 2009
- ^coffeescript.orgAnnouncing CoffeeScript 2
- ^CoffeeScript calls this "pattern matching",which is a non-standard use of that term.
- ^"Official CoffeeScript Page".Retrieved20 November2013.
- ^"The Problem with Implicit Scoping in CoffeeScript".Retrieved2018-10-13.
- ^"CoffeeScript's Scoping is Madness".25 July 2013.Retrieved2018-10-13.
- ^CoffeeScriptArchived2012-04-27 at theWayback Machine.Jashkenas.github.com. Retrieved on 2013-07-21.
- ^Sta Cruz, Rico."js2coffee".Retrieved11 May2014.
- ^"Official IcedCoffeeScript website".
- ^Wheeler, Dan; Mahkovec, Ziga; Varenhorst, Chris (13 September 2012)."Dropbox dives into CoffeeScript".Retrieved11 May2013.
- ^Goldstein, David (13 May 2020)."The Great CoffeeScript to Typescript Migration of 2017".Dropbox.Tech.Retrieved30 June2020.
- ^"JavaScript · Styleguide · GitHub".Github.com. Archived fromthe originalon 2013-08-15.Retrieved2015-11-30.
- ^"Atom source code".GitHub.Retrieved2021-06-26.
- ^"Basic Customization".AtomFlight Manual.GitHub.Archivedfrom the original on 2024-04-29.Retrieved29 April2024.
- ^Cullen, Daniel."PIXEL GAME MAKER MV (PC)".Christ Centered Gaming.Retrieved15 January2021.
Further reading
edit- Lee, Patrick (May 14, 2014).CoffeeScript in Action(First ed.).Manning Publications.p. 432.ISBN978-1617290626.
- Grosenbach, Geoffrey (May 12, 2011). "Meet CoffeeScript" (First ed.).PeepCode.
{{cite journal}}
:Cite journal requires|journal=
(help) - Bates, Mark (May 31, 2012).Programming in CoffeeScript(First ed.).Addison-Wesley.p. 350.ISBN978-0-321-82010-5.
- MacCaw, Alex (January 31, 2012).The Little Book on CoffeeScript(First ed.).O'Reilly Media.p. 62.ISBN978-1449321055.
- Burnham, Trevor (August 3, 2011).CoffeeScript: Accelerated JavaScript Development(First ed.).Pragmatic Bookshelf.p.138.ISBN978-1934356784.