CoffeeScript

Last updated
CoffeeScript
CoffeeScript-logo.svg
Paradigm Multi-paradigm: prototype-based, functional, imperative, scripting
Designed by Jeremy Ashkenas
Developer Jeremy Ashkenas
First appearedDecember 13, 2009;14 years ago (2009-12-13)
Stable release
2.7.0 [1]   OOjs UI icon edit-ltr-progressive.svg / 24 April 2022;22 months ago (24 April 2022)
Typing discipline dynamic, implicit
OS Cross-platform
License MIT License
Filename extensions .coffee, .litcoffee[ citation needed ]
Website coffeescript.org
Influenced by
Haskell, JavaScript, Perl,[ citation needed ] Python, [2] Ruby, YAML [3]
Influenced
MoonScript, LiveScript, JavaScript

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. [4] Specific additional features include list comprehension and destructuring assignment.

Contents

CoffeeScript support is included in Ruby on Rails version 3.1 [5] and Play Framework. [6] In 2011, Brendan Eich referenced CoffeeScript as an influence on his thoughts about the future of JavaScript. [7] [8]

History

On December 13, 2009, Jeremy Ashkenas made the first Git commit 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 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. [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

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 and Ruby, these control statements also have postfix versions; for example, if can also be written in consequent 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 the body mass index in JavaScript, one could write:

constmass=72;constheight=1.78;constBMI=mass/height**2;if(18.5<=BMI&&BMI<25){alert('You are healthy!')}

With CoffeeScript the interval is directly described:

mass=72height=1.78BMI=mass/height**2alert'You are healthy!'if18.5<=BMI<25

To compute the greatest common divisor of two integers with the Euclidean algorithm, in JavaScript one usually needs a while loop:

gcd=(x,y)=>{do{[x,y]=[y,x%y];}while(y!==0)returnx;}

Whereas in CoffeeScript one can use until [13] instead:

gcd=(x, y) ->[x,y]=[y,x%y]untilyis0x

The ? keyword quickly checks if a variable is null or undefined :

personCheck=->ifnotperson?thenalert("No person")elsealert("Have person")person=nullpersonCheck()person="Ivan"personCheck()

This would alert "No person" if the variable is null or undefined and "Have person" if there is something there.

A common pre-es6 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, 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 π"

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 whose remainder modulo 2 is 1), one can do:

alertn*nfornin[1..10]whenn%2is1

Alternatively, there is:

alertn*nfornin[1..10]by2

A linear search can be implemented with a one-liner using the when keyword:

names=["Ivan","Joanna","Nikolay","Mihaela"]linearSearch=(searchName) ->alert(name)fornameinnameswhennameissearchName

The for ... in syntax allows looping over arrays while the for ... of syntax allows looping over objects.

CoffeeScript has been criticized for its unusual scoping rules. [15] [16] In particular, it completely disallows variable shadowing which makes reasoning about code more difficult and error-prone in some basic programming patterns established by and taken for granted since procedural programming principles 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 possible foo 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

The CoffeeScript compiler has been self-hosting 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. [17] One alternative to the Node.js utility is the Coffee Maven Plugin, a plugin for the Apache Maven build system. The plugin uses the Rhino JavaScript engine written in Java.[ 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

Extensions

Iced CoffeeScript is a superset of CoffeeScript which adds two new keywords: await and defer. These additions simplify asynchronous control flow, making the code look more like a procedural programming language, eliminating the call-back chain. It can be used on the server side and in the browser. [19]

Adoption

On September 13, 2012, Dropbox announced that their browser-side code base had been rewritten from JavaScript to CoffeeScript, [20] however it was migrated to TypeScript in 2017. [21]

GitHub's internal style guide once said "write new JS in CoffeeScript", though it no longer does, [22] and their Atom text editor was also written in the language. [23]

Pixel Game Maker MV makes uses of CoffeeScript as part of its game development environment. [24]

See also

Related Research Articles

<span class="mw-page-title-main">JavaScript</span> High-level programming language

JavaScript, often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. As of 2024, 98.8% of websites use JavaScript on the client side for webpage behavior, often incorporating third-party libraries. All major web browsers have a dedicated JavaScript engine to execute the code on users' devices.

<span class="mw-page-title-main">Ruby (programming language)</span> General-purpose programming language

Ruby is an interpreted, high-level, general-purpose programming language that supports multiple programming paradigms. It was designed with an emphasis on programming productivity and simplicity. In Ruby, everything is an object, including primitive data types. It was developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.

In computer programming, the scope of a name binding is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts of the program, the name may refer to a different entity, or to nothing at all. Scope helps prevent name collisions by allowing the same name to refer to different objects – as long as the names have separate scopes. The scope of a name binding is also known as the visibility of an entity, particularly in older or more technical literature—this is in relation to the referenced entity, not the referencing name.

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function together with an environment. The environment is a mapping associating each free variable of the function with the value or reference to which the name was bound when the closure was created. Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

ECMAScript is a standard for scripting languages, including JavaScript, JScript, and ActionScript. It is best known as a JavaScript standard intended to ensure the interoperability of web pages across different web browsers. It is standardized by Ecma International in the document ECMA-262.

In object-oriented (OO) and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.

<span class="mw-page-title-main">Conditional (computer programming)</span> Control flow statement that executes code according to some condition(s)

In computer science, conditionals are programming language commands for handling decisions. Specifically, conditionals perform different computations or actions depending on whether a programmer-defined Boolean condition evaluates to true or false. In terms of control flow, the decision is always achieved by selectively altering the control flow based on some condition . Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime. Conditional statements are the checkpoints in the programme that determines behaviour according to situation.

In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, ternary if, or inline if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is by far and large the most common, but alternative syntaxes do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

In some programming languages, const is a type qualifier, which indicates that the data is read-only. While this can be used to declare constants, const in the C family of languages differs from similar constructs in other languages in that it is part of the type, and thus has complicated behavior when combined with pointers, references, composite data types, and type-checking. In other languages, the data is not in a single memory location, but copied at compile time for each use. Languages which use it include C, C++, D, JavaScript, Julia, and Rust.

In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

this, self, and Me are keywords used in some computer programming languages to refer to the object, class, or other entity which the currently running code is a part of. The entity referred to thus depends on the execution context. Different programming languages use these keywords in slightly different ways. In languages where a keyword like "this" is mandatory, the keyword is the only way to access data and methods stored in the current object. Where optional, these keywords can disambiguate variables and functions with the same name.

The C and C++ programming languages are closely related but have many significant differences. C++ began as a fork of an early, pre-standardized C, and was designed to be mostly source-and-link compatible with C compilers of the time. Due to this, development tools for the two languages are often integrated into a single product, with the programmer able to specify C or C++ as their source language.

Haxe is a high-level cross-platform programming language and compiler that can produce applications and source code for many different computing platforms from one code-base. It is free and open-source software, released under the MIT License. The compiler, written in OCaml, is released under the GNU General Public License (GPL) version 2.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

In computer programming, a constant is a value that is not altered by the program during normal execution. When associated with an identifier, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution. To simplify, constants' values remains, while the values of variables varies, both hence their names.

Underscore.js is a JavaScript library which provides utility functions for common programming tasks. It is comparable to features provided by Prototype.js and the Ruby language, but opts for a functional programming design instead of extending object prototypes. The documentation refers to Underscore.js as "the tie to go along with jQuery's tux, and Backbone.js' suspenders." Underscore.js was created by Jeremy Ashkenas, who is also known for Backbone.js and CoffeeScript.

Kotlin is a cross-platform, statically typed, general-purpose high-level programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin's standard library depends on the Java Class Library, but type inference allows its syntax to be more concise. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code via LLVM. Language development costs are borne by JetBrains, while the Kotlin Foundation protects the Kotlin trademark.

<span class="mw-page-title-main">Nim (programming language)</span> Programming language

Nim is a general-purpose, multi-paradigm, statically typed, compiled high-level systems programming language, designed and developed by a team around Andreas Rumpf. Nim is designed to be "efficient, expressive, and elegant", supporting metaprogramming, functional, message passing, procedural, and object-oriented programming styles by providing several features such as compile time code generation, algebraic data types, a foreign function interface (FFI) with C, C++, Objective-C, and JavaScript, and supporting compiling to those same languages as intermediate representations.

References

  1. "2.7.0". 24 April 2022. Retrieved 9 August 2022.
  2. https://coffeescript.org/ "CoffeeScript borrows chained comparisons from Python"
  3. Heller, Martin (October 18, 2011). "Turn up your nose at Dart and smell the CoffeeScript". InfoWorld . Retrieved 2020-07-15.
  4. Alex MacCaw (January 2012). The Little Book on CoffeScript. O'Reilly Media. ISBN   978-1-4493-2105-5.
  5. Josh Peek (April 13, 2011). "Tweet by Rails Core Team Member".
  6. "AssetsCoffeeScript - 2.5.x". www.playframework.com. Retrieved 2016-10-31.
  7. Eich, Brendan. "Harmony of My Dreams"
  8. Eich, Brendan. "My JSConf.US Presentation"
  9. Github. 'initial commit of the mystery language'
  10. Hacker News. CoffeeScript 1.0.0 announcement posted by Jeremy Ashkenas on Dec 24, 2010
  11. Hacker News. Original CoffeeScript announcement posted by Jeremy Ashkenas on Dec 24, 2009
  12. coffeescript.org Announcing CoffeeScript 2
  13. CoffeeScript calls this "pattern matching", which is a non-standard use of that term.
  14. "Official CoffeeScript Page" . Retrieved 20 November 2013.
  15. "The Problem with Implicit Scoping in CoffeeScript" . Retrieved 2018-10-13.
  16. "CoffeeScript's Scoping is Madness" . Retrieved 2018-10-13.
  17. CoffeeScript Archived 2012-04-27 at the Wayback Machine . Jashkenas.github.com. Retrieved on 2013-07-21.
  18. Sta Cruz, Rico. "js2coffee" . Retrieved 11 May 2014.
  19. "Official IcedCoffeeScript website".
  20. Wheeler, Dan; Mahkovec, Ziga; Varenhorst, Chris (13 September 2012). "Dropbox dives into CoffeeScript" . Retrieved 11 May 2013.
  21. Goldstein, David (13 May 2020). "The Great CoffeeScript to Typescript Migration of 2017". Dropbox.Tech. Retrieved 30 June 2020.
  22. "JavaScript · Styleguide · GitHub". Github.com. Archived from the original on 2013-08-15. Retrieved 2015-11-30.
  23. Atom source code. github.com. Retrieved on 2021-06-26.
  24. Cullen, Daniel. "PIXEL GAME MAKER MV (PC)". Christ Centered Gaming. Retrieved 15 January 2021.

Further reading