version
of coffee is available as a Node.js utility, requiring Node 6 or later. The core compiler however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see Try CoffeeScript).npm install --global coffeescript
coffee
and cake
commands available globally.CoffeeScript
in a project, you should install it locally for that project so that the version of CoffeeScript
is tracked as one of your project’s dependencies. Within that project’s folder:npm install --save-dev coffeescript
coffee
and cake
commands will first look in the current folder to see if CoffeeScript is installed locally, and use that version if so. This allows different versions of CoffeeScript to be installed globally and locally.--transpile
option (see Transpilation) you will need to also install @babel/core
either globally or locally, depending on whether you are running a globally or locally installed version of CoffeeScript.=>
becomes a JS =>
, a CoffeeScript class
becomes a JS class
and so on. Major new features in CoffeeScript 2 include async functions and JSX. You can read more in the announcement.scripts
, compile .coffee
files into .js
, and provide an interactive REPL. The coffee command takes the following options :Option | Description |
---|---|
-c, --compile |
Compile a .coffee script into a .js JavaScript file of the same name. |
-t, --transpile |
Pipe the CoffeeScript compiler’s output through Babel before saving or running the generated JavaScript. Requires @babel/core to be installed, and options to pass to Babel in a .babelrc file or a package.json with a babel key in the path of the file or folder to be compiled. See Transpilation. |
-m, --map |
Generate source maps alongside the compiled JavaScript files. Adds sourceMappingURL directives to the JavaScript as well. |
-M, --inline-map |
Just like --map , but include the source map directly in the compiled JavaScript files, rather than in a separate file. |
-i, --interactive |
Launch an interactive CoffeeScript session to try short snippets. Identical to calling coffee with no arguments. |
-o, --output [DIR] |
Write out all compiled JavaScript files into the specified directory. Use in conjunction with --compile or --watch . |
-w, --watch |
Watch files for changes, rerunning the specified command when any file is updated. |
-p, --print |
Instead of writing out the JavaScript as a file, print it directly to stdout. |
-s, --stdio |
Pipe in CoffeeScript to STDIN and get back JavaScript over STDOUT. Good for use with processes written in other languages. An example:cat src/cake.coffee | coffee -sc |
-l, --literate |
Parses the code as Literate CoffeeScript. You only need to specify this when passing in code directly over stdio, or using some sort of extension-less file name. |
-e, --eval |
Compile and print a little snippet of CoffeeScript directly from the command line. For example:coffee -e "console.log num for num in [10..1]" |
-r, --require [MODULE] |
require() the given module before starting the REPL or evaluating the code given with the --eval flag. |
-b, --bare |
Compile the JavaScript without the top-level function safety wrapper. |
--no-header |
Suppress the “Generated by CoffeeScript” header. |
--nodejs |
The node executable has some useful options you can set, such as --debug , --debug-brk , --max-stack-size , and --expose-gc . Use this flag to forward options directly to Node.js. To pass multiple flags, use --nodejs multiple times. |
--ast |
Generate an abstract syntax tree of nodes of the CoffeeScript. Used for integrating with JavaScript build tools. |
--tokens |
Instead of parsing the CoffeeScript, just lex it, and print out the token stream. Used for debugging the compiler. |
-n, --nodes |
Instead of compiling the CoffeeScript, just lex and parse it, and print out the parse tree. Used for debugging the compiler. |
--transpile
command-line option or the transpile
Node API option. To use either, @babel/core
must be installed in your project :npm install --save-dev @babel/core
coffee
command outside of a project folder, using a globally-installed coffeescript
module, @babel/core
needs to be installed globally :npm install --global @babel/core
.babelrc
file would be just { "presets": ["@babel/env"] }
. This implies that you have installed @babel/preset-env :npm install --save-dev @babel/preset-env # Or --global for non-project-based usage
->
square = (x) -> x * x
cube = (x) -> square(x) * x
var cube, square;
​
square = function(x) {
return x * x;
};
​
cube = function(x) {
return square(x) * x;
};​
undefined
).fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
var fill;
​
fill = function(container, liquid = "coffee") {
return `Filling the ${container} with ${liquid}...`;
};​
#
character to the end of a line, or from ###
to the next appearance of ###
. Comments are ignored by the compiler, though the compiler makes its best effort at reinserting your comments into the output JavaScript after compilation.###
Fortune Cookie Reader v1.0
Released under the MIT License
###
​
sayFortune = (fortune) ->
console.log fortune # in bed!
​
/*
Fortune Cookie Reader v1.0
Released under the MIT License
*/
var sayFortune;
​
sayFortune = function(fortune) {
return console.log(fortune); // in bed!
};
###
comments make type annotations possible. " or '
characters. CoffeeScript also supports string interpolation within "-
quoted strings, using #{ … }
. Single-quoted strings are literal. You may even use interpolation in object keys.author = "Wittgenstein"
quote = "A picture is a fact. -- #{ author }"
​
sentence = "#{ 22 / 7 } is a decent approximation of π"
var author, quote, sentence;
​
author = "Wittgenstein";
​
quote = `A picture is a fact. -- ${author}`;
​
sentence = `${22 / 7} is a decent approximation of π`;​
mobyDick = "Call me Ishmael. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."
var mobyDick;
​
mobyDick = "Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse,
and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world...";​
""" or '''
, can be used to hold formatted or indentation-sensitive text (or, if you just don’t feel like escaping quotes and apostrophes). The indentation level that begins the block is maintained throughout, so you can keep it all aligned with the body of your code.html = """
<strong>
cup of coffeescript
</strong>
"""​
var html;
​
html = `<strong>
cup of coffeescript
</strong>`;
​Double-quoted block strings, like other double-quoted strings, allow interpolation.
​
song = ["do", "re", "mi", "fa", "so"]
​
singers = {Jagger: "Rock", Elvis: "Roll"}
​
bitlist = [
1, 0, 1
0, 0, 1
1, 1, 0
]
​
kids =
brother:
name: "Max"
age: 11
sister:
name: "Ida"
age: 9
var bitlist, kids, singers, song;
​
song = ["do", "re", "mi", "fa", "so"];
​
singers = {
Jagger: "Rock",
Elvis: "Roll"
};
​
bitlist = [1, 0, 1, 0, 0, 1, 1, 1, 0];
​
kids = {
brother: {
name: "Max",
age: 11
},
sister: {
name: "Ida",
age: 9
}
};
{
and }
are required for this shorthand.name = "Michelangelo"
mask = "orange"
weapon = "nunchuks"
turtle = {name, mask, weapon}
output = "#{turtle.name} wears an #{turtle.mask} mask. Watch out for his #{turtle.weapon}!"
var mask, name, output, turtle, weapon;
​
name = "Michelangelo";
​
mask = "orange";
​
weapon = "nunchuks";
​
turtle = {name, mask, weapon};
​
output = `${turtle.name} wears an ${turtle.mask} mask. Watch out for his ${turtle.weapon}!`;
CoffeScript | TypeScript |
---|---|
It is best used when we want more readable code and lots of syntactic sugar. | It is best used when we want optional static typing and better tool support. |
It is used for server-side web applications only. | It is used for both server-side and client-side web applications. |
It is developed and maintained by the Open Source developer community itself under the MIT License. | It is developed and maintained by Microsoft under the Apache2 License. |
“”
), a hash tag(#
), and a pair of curly braces({}
). The string is to be declared inside the double quotes and the variable that is to be interpolated is placed within the curly braces that are after hashtag symbol.name = "FtL"
message = " Hello from #{name} "
“”
).name = ["sarthak","surabhi", "tejal",
"dipali", "girija", "devendra"]
department = {
id : 10,
branch : "computer"
}
skills =
designer :
name : "ali"
surname : "bazzi"
backend :
name : "sunny"
surname : "warner"
map()
is used when we want to transformed each value of the array and want to get new array out of it. The map is just used to map or track the value of the arrayengineers = [
{ name : "ali" , surname : "bazzi"},
{ name : "virat" , surname : "sharma"},
{ name : "sharma" , surname : "pandey"},
{ name : "paresh" , surname : "vikramadity"},
{ name : "sandip" , surname : "jain"}
]
names_record = engineers.map(firstname) -> firstname.name
console.log(names_record)
Output:
['ali', 'virat', 'sharma', 'paresh', 'sandip']
+
operator between the two strings.new_string = "Hello how are you "+"Welcome to Free Time Learn".
console.log new_String
On compiling the above CoffeeScript code compiler will generate corresponding javascript code as follows :
// Generated by CoffeeScript 1.10.0
(function() {
var new_string;
new_string = "Hello how are you " + "Welcome to Interview Questions";
console.log(new_String);
}).call(this);
charAt()
: This method returns the character at the given index value of a string object.charCodeAt()
: This method returns the Unicode value of the character at the given index.oncat()
: This method combines two substrings and returns a superstring.indexOf()
: This method returns the index of calling string having the first occurrence of a specified value, It will return -1 if not found.lastIndexOf()
: This method returns the index of calling string having the last occurrence of a specified value, It will return -1 if not found.localeCompare()
: This method returns a number representing whether a reference string comes before or after or is the same as given string in sort order.match()
: This method is used to match a regular expression against a string.search()
: This method executes a search for a match between the regular expressions in a specified string.slice()
: Extract the section of a string object and returns a new string object.split()
: Splits a string object into the array of strings by separating the string into substrings.substr()
: This method returns the calling string beginning at the specified location through the specified number of characters.toLocaleLowerCase()
: Converts the calling string into the lower case while respecting the current locale.toLocaleUpperCase()
: Converts calling string into the upper case while respecting the current locale.toLowerCase()
: Returns calling string in lower case.ToUpperCase()
: Returns calling string in upper case.var
yourself.outer = 1
changeNumbers = ->
inner = -1
outer = 10
inner = changeNumbers()​
var changeNumbers, inner, outer;
​
outer = 1;
​
changeNumbers = function() {
var inner;
inner = -1;
return outer = 10;
};
​
inner = changeNumbers();​
outer
is not redeclared within the inner function, because it’s already in scope; inner
within the function, on the other hand, should not be able to change the value of the external variable of the same name, and therefore has a declaration of its own.if/else
statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, multi-line
conditionals are delimited by indentation. There’s also a handy postfix form, with the if
or unless
at the end.if
statements into JavaScript expressions, using the ternary operator when possible, and closure
wrapping otherwise. There is no explicit ternary statement in CoffeeScript — you simply use a regular if
statement on a single line.mood = greatlyImproved if singing
​
if happy and knowsIt
clapsHands()
chaChaCha()
else
showIt()
​
date = if friday then sue else jill
var date, mood;
​
if (singing) {
mood = greatlyImproved;
}
​
if (happy && knowsIt) {
clapsHands();
chaChaCha();
} else {
showIt();
}
​
date = friday ? sue : jill;
...
) after the variable name.indian_team = (first, second, others...) ->
Captain = first
WiseCaptain = second
team = others
console.log "Captain: " +Captain
console.log "Wise captain: " +WiseCaptain
console.log "Other team members: " +team
#Passing 4 arguments
console.log "############## Four Players ############"
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma"
#Passing 6 arguments
console.log "############## Six Players ############"
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan"
#Passing full squad
console.log "############## Full squad #############"
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"
arrays
, objects
, and ranges
. Comprehensions replace (and compile into) for loops
, with optional guard clauses and the value of the current array index
. Unlike for loops
, array comprehensions
are expressions
, and can be returned and assigned.# Eat lunch.
eat = (food) -> "#{food} eaten."
eat food for food in ['toast', 'cheese', 'wine']
​
# Fine five course dining.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu = (i, dish) -> "Menu Item #{i}: #{dish}"
menu i + 1, dish for dish, i in courses
​
# Health conscious meal.
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
// Eat lunch.
var courses, dish, eat, food, foods, i, j, k, l, len, len1, len2, menu, ref;
​
eat = function(food) {
return `${food} eaten.`;
};
​
ref = ['toast', 'cheese', 'wine'];
for (j = 0, len = ref.length; j < len; j++) {
food = ref[j];
eat(food);
}
​
// Fine five course dining.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'];
​
menu = function(i, dish) {
return `Menu Item ${i}: ${dish}`;
};
​
for (i = k = 0, len1 = courses.length; k < len1; i = ++k) {
dish = courses[i];
menu(i + 1, dish);
}
​
// Health conscious meal.
foods = ['broccoli', 'spinach', 'chocolate'];
​
for (l = 0, len2 = foods.length; l < len2; l++) {
food = foods[l];
if (food !== 'chocolate') {
eat(food);
}
}​
loop
, each/forEach
, map
, or select/filter
, for example :shortNames = (name for name in list when name.length < 5)
splats
with tailing argument refer to the argument placed after the splat argument
.indian_team = (first, second, others...., last) ->
Captain = first
WiseCaptain = second
team = others
Wicketkeeper =last
console.log "Captain: " +Captain
console.log "Wise captain: " +WiseCaptain
console.log "Wicket keeper is:"+last
console.log "Other team members: " +team
squad = [
"Mahendra Singh Dhoni"
"Virat Kohli"
"Shikhar Dhawan"
"Rohit Sharma"
"Gurkeerat Singh Mann"
"Rishi Dhawan"
"R Ashwin"
"Ravindra Jadeja"
"Axar Patel"
"Jasprit Bumrah"
"Umesh Yadav"
"Harbhajan Singh"
"Ashish Nehra"
"Hardik Pandya"
"Suresh Raina"
"Yuvraj Singh"
"Ajinkya Rahane"
]​
indian_team
function.CoffeeScript
code. Hence we can use all the methods of math object in javascript.math function
present in the math object
:abs()
: This function returns the absolute value of a number.atan2()
: This function returns arctangent of the quotient of its arguments.ceil()
: This function returns the smallest integer greater than or equal to the given number.cos()
: This function returns the cosin of the given number.exp()
: This function returns EN, Where N is the argument, and E is the Euler's constant, the base of the natural logarithm.floor()
: This function returns the largest integer less than equal to the number.log()
: This function returns natural logarithm (base E) of a number.max()
: This function returns largest of zero or more numbers.min()
: This function returns the smallest of zero or more numbers.pow()
: This function returns the base exponent of the given number.random()
: This function returns the pseudo-random number between 0 and 1.round()
: This function returns the value of the number rounded to the nearest integer.sin()
: This function returns the sine of the given number.sqrt()
: This function returns the square root of the specified number.tan()
: This function returns the tangent of the specified number.3..6
), the range is inclusive (3, 4, 5, 6
); with three dots (3...6
), the range excludes the end (3, 4, 5
). Slices
indices have useful defaults. An omitted first index
defaults to zero and an omitted second index
defaults to the size of the array.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
​
start = numbers[0..2]
​
middle = numbers[3...-2]
​
end = numbers[-2..]
​
copy = numbers[..]​
var copy, end, middle, numbers, start;
​
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
​
start = numbers.slice(0, 3);
​
middle = numbers.slice(3, -2);
​
end = numbers.slice(-2);
​
copy = numbers.slice(0);​
​splicing
it.numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
​
numbers[3..6] = [-3, -4, -5, -6]​
var numbers, ref,
splice = [].splice;
​
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
​
splice.apply(numbers, [3, 4].concat(ref = [-3, -4, -5, -6])), ref;
Note that JavaScript strings are immutable, and can’t be spliced.
==
operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, CoffeeScript compiles ==
into ===
, and !=
into !==
. In addition, is
compiles into ===
, and isnt
into !==
.not
as an alias for !
.and
compiles to &&
, and or into ||
.while
, if/else
, and switch/when
statements.on
and yes
are the same as boolean true
, while off
and no
are boolean false
.unless
can be used as the inverse of if
.in
to test for array presence, and of
to test for JavaScript object-key presence.for
loop, from
compiles to the ES2015 of
. (Yes, it’s unfortunate; the CoffeeScript of
predates the ES2015 of
.)**
can be used for exponentiation and //
performs floor division. %
works just like in JavaScript, while %%
provides “dividend dependent modulo”:-7 % 5 == -2 # The remainder of 7 / 5
-7 %% 5 == 3 # n %% 5 is always between 0 and 4
​
tabs.selectTabAtIndex((tabs.currentIndex - count) %% tabs.length)
var modulo = function(a, b) { return (+a % (b = +b) + b) % b; };
​
-7 % 5 === -2; // The remainder of 7 / 5
​
modulo(-7, 5) === 3; // n %% 5 is always between 0 and 4
​
tabs.selectTabAtIndex(modulo(tabs.currentIndex - count, tabs.length));​
All together now :
CoffeeScript | JavaScript |
---|---|
is |
=== |
isnt |
!== |
not |
! |
and |
&& |
or |
|| |
true , yes , on |
true |
false , no , off |
false |
@ , this |
this |
a in b |
[].indexOf.call(b, a) >= 0 |
a of b |
a in b |
for a from b |
for (a of b) |
a ** b |
a ** b |
a // b |
Math.floor(a / b) |
a %% b |
(a % b + b) % b |
await keyword
. Like with generators, there’s no need for an async keyword;
an async function in CoffeeScript is simply a function that awaits
.yield return
forces a generator, await return
may be used to force a function to be async
.# Your browser must support async/await and speech synthesis
# to run this example.
sleep = (ms) ->
new Promise (resolve) ->
window.setTimeout resolve, ms
​
say = (text) ->
window.speechSynthesis.cancel()
window.speechSynthesis.speak new SpeechSynthesisUtterance text
​
countdown = (seconds) ->
for i in [seconds..1]
say i
await sleep 1000 # wait one second
say "Blastoff!"
​
countdown 3​
// Your browser must support async/await and speech synthesis
// to run this example.
var countdown, say, sleep;
​
sleep = function(ms) {
return new Promise(function(resolve) {
return window.setTimeout(resolve, ms);
});
};
​
say = function(text) {
window.speechSynthesis.cancel();
return window.speechSynthesis.speak(new SpeechSynthesisUtterance(text));
};
​
countdown = async function(seconds) {
var i, j, ref;
for (i = j = ref = seconds; (ref <= 1 ? j <= 1 : j >= 1); i = ref <= 1 ? ++j : --j) {
say(i);
await sleep(1000); // wait one second
}
return say("Blastoff!");
};
​
countdown(3);
class
and extends
keywords as syntactic sugar for working with prototypal functions. With ES2015, JavaScript has adopted those keywords
; so CoffeeScript 2 compiles its class
and extends
keywords to ES2015 classes
.class Animal
constructor: (@name) ->
​
move: (meters) ->
alert @name + " moved #{meters}m."
​
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
​
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
​
sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
​
sam.move()
tom.move()
var Animal, Horse, Snake, sam, tom;
​
Animal = class Animal {
constructor(name) {
this.name = name;
}
​
move(meters) {
return alert(this.name + ` moved ${meters}m.`);
}
​
};
​
Snake = class Snake extends Animal {
move() {
alert("Slithering...");
return super.move(5);
}
​
};
​
Horse = class Horse extends Animal {
move() {
alert("Galloping...");
return super.move(45);
}
​
};
​
sam = new Snake("Sammy the Python");
​
tom = new Horse("Tommy the Palomino");
​
sam.move();
​
tom.move();​
@
before the method name:class Teenager
@say: (speech) ->
words = speech.split ' '
fillers = ['uh', 'um', 'like', 'actually', 'so', 'maybe']
output = []
for word, index in words
output.push word
output.push fillers[Math.floor(Math.random() * fillers.length)] unless index is words.length - 1
output.join ', '
​
var Teenager;
​
Teenager = class Teenager {
static say(speech) {
var fillers, i, index, len, output, word, words;
words = speech.split(' ');
fillers = ['uh', 'um', 'like', 'actually', 'so', 'maybe'];
output = [];
for (index = i = 0, len = words.length; i < len; index = ++i) {
word = words[index];
output.push(word);
if (index !== words.length - 1) {
output.push(fillers[Math.floor(Math.random() * fillers.length)]);
}
}
return output.join(', ');
}
​
};​
​class
definitions are blocks of executable code, which make for interesting metaprogramming possibilities. In the context of a class definition, this
is the class object itself; therefore, you can assign static properties by using @property: value
.classes
, CoffeeScript provides a shortcut for working with prototypes
. The ::
operator gives you quick access to an object’s prototype :String::dasherize = ->
this.replace /_/g, "-"
​
String.prototype.dasherize = function() {
return this.replace(/_/g, "-");
};
switch
statements in JavaScript are a bit awkward. You need to remember to break
at the end of every case
statement to avoid accidentally falling through to the default case
. CoffeeScript prevents accidental fall-through, and can convert the switch
into a returnable, assignable expression. The format is: switch
condition, when
clauses, else
the default case.switch
statements in CoffeeScript can take multiple values for each when
clause. If any of the values match, the clause runs.switch day
when "Mon" then go work
when "Tue" then go relax
when "Thu" then go iceFishing
when "Fri", "Sat"
if day is bingoDay
go bingo
go dancing
when "Sun" then go church
else go work
​
switch (day) {
case "Mon":
go(work);
break;
case "Tue":
go(relax);
break;
case "Thu":
go(iceFishing);
break;
case "Fri":
case "Sat":
if (day === bingoDay) {
go(bingo);
go(dancing);
}
break;
case "Sun":
go(church);
break;
default:
go(work);
}​
switch
statements can also be used without a control expression, turning them in to a cleaner alternative to if/else
chains.score = 76
grade = switch
when score < 60 then 'F'
when score < 70 then 'D'
when score < 80 then 'C'
when score < 90 then 'B'
else 'A'
# grade == 'C'
​
var grade, score;
​
score = 76;
​
grade = (function() {
switch (false) {
case !(score < 60):
return 'F';
case !(score < 70):
return 'D';
case !(score < 80):
return 'C';
case !(score < 90):
return 'B';
default:
return 'A';
}
})();
​
// grade == 'C'
try
expressions have the same semantics as try
statements in JavaScript, though in CoffeeScript, you may omit both the catch
and finally
parts. The catch
part may also omit the error parameter if it is not needed.try
allHellBreaksLoose()
catsAndDogsLivingTogether()
catch error
print error
finally
cleanUp()
​
var error;
​
try {
allHellBreaksLoose();
catsAndDogsLivingTogether();
} catch (error1) {
error = error1;
print(error);
} finally {
cleanUp();
}
block
strings and comments, CoffeeScript supports block regexes
—
extended regular expressions that ignore internal whitespace and can contain comments and interpolation. Modeled after Perl’s /x
modifier, CoffeeScript’s block regexes are delimited by ///
and go a long way towards making complex regular expressions readable. To quote from the CoffeeScript source:NUMBER = ///
^ 0b[01]+ | # binary
^ 0o[0-7]+ | # octal
^ 0x[\da-f]+ | # hex
^ \d*\.?\d+ (?:e[+-]?\d+)? # decimal
///i
​
var NUMBER;
​
NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i; // binary
// octal
// hex
// decimal
import
and export
syntax :import './local-file.js' # Must be the filename of the generated file
import 'package'
​
import _ from 'underscore'
import * as underscore from 'underscore'
​
import { now } from 'underscore'
import { now as currentTimestamp } from 'underscore'
import { first, last } from 'underscore'
import utilityBelt, { each } from 'underscore'
​
import dates from './calendar.json' assert { type: 'json' }
​
export default Math
export square = (x) -> x * x
export class Mathematics
least: (x, y) -> if x < y then x else y
​
export { sqrt }
export { sqrt as squareRoot }
export { Mathematics as default, sqrt as squareRoot }
​
export * from 'underscore'
export { max, min } from 'underscore'
export { version } from './package.json' assert { type: 'json' }
import './local-file.js';
​
import 'package';
​
import _ from 'underscore';
​
import * as underscore from 'underscore';
​
import {
now
} from 'underscore';
​
import {
now as currentTimestamp
} from 'underscore';
​
import {
first,
last
} from 'underscore';
​
import utilityBelt, {
each
} from 'underscore';
​
import dates from './calendar.json' assert {
type: 'json'
};
​
export default Math;
​
export var square = function(x) {
return x * x;
};
​
export var Mathematics = class Mathematics {
least(x, y) {
if (x < y) {
return x;
} else {
return y;
}
}
​
};
​
export {
sqrt
};
​
export {
sqrt as squareRoot
};
​
export {
Mathematics as default,
sqrt as squareRoot
};
​
export * from 'underscore';
​
export {
max,
min
} from 'underscore';
​
export {
version
} from './package.json' assert {
type: 'json'
};
# Your browser must support dynamic import to run this example.
​
do ->
{ run } = await import('./browser-compiler-modern/coffeescript.js')
run '''
if 5 < new Date().getHours() < 9
alert 'Time to make the coffee!'
else
alert 'Time to get some work done.'
'''
// Your browser must support dynamic import to run this example.
(async function() {
var run;
({run} = (await import('./browser-compiler-modern/coffeescript.js')));
return run(`if 5 < new Date().getHours() < 9
alert 'Time to make the coffee!'
else
alert 'Time to get some work done.'`);
})();
CoffeeScript
, you can use backticks
to pass it straight
through.hi = `function() {
return [document.title, "Hello JavaScript"].join(": ");
}`
​
var hi;
​
hi = function() {
return [document.title, "Hello JavaScript"].join(": ");
};
\`​
becomes `
​.\\\`
​ becomes \`
​.markdown = `function () {
return \`In Markdown, write code like \\\`this\\\`\`;
}`
​
var markdown;
​
markdown = function () {
return `In Markdown, write code like \`this\``;
};​
​backticks
. That’s easier than escaping backticks, if you need them inside your JavaScript block.```
function time() {
return `The time is ${new Date().toLocaleTimeString()}`;
}
```
​
function time() {
return `The time is ${new Date().toLocaleTimeString()}`;
}
;
React.createElement
calls or any code specific to React or any other framework. It is up to you to attach another step in your build chain to convert this JSX to whatever function calls you wish the XML elements to compile to.<
and >
. You can interpolate CoffeeScript code inside a tag using {
and }
. To avoid compiler errors, when using <
and >
to mean “less than” or “greater than,” you should wrap the operators in spaces to distinguish them from XML tags. So i < len
, not i<len
. The compiler tries to be forgiving when it can be sure what you intend, but always putting spaces around the “less than” and “greater than” operators will remove ambiguity.renderStarRating = ({ rating, maxStars }) ->
<aside title={"Rating: #{rating} of #{maxStars} stars"}>
{for wholeStar in [0...Math.floor(rating)]
<Star className="wholeStar" key={wholeStar} />}
{if rating % 1 isnt 0
<Star className="halfStar" />}
{for emptyStar in [Math.ceil(rating)...maxStars]
<Star className="emptyStar" key={emptyStar} />}
</aside>
​
var renderStarRating;
​
renderStarRating = function({rating, maxStars}) {
var emptyStar, wholeStar;
return <aside title={`Rating: ${rating} of ${maxStars} stars`}>
{(function() {
var i, ref, results;
results = [];
for (wholeStar = i = 0, ref = Math.floor(rating); (0 <= ref ? i < ref : i > ref); wholeStar = 0 <= ref ? ++i : --i) {
results.push(<Star className="wholeStar" key={wholeStar} />);
}
return results;
})()}
{rating % 1 !== 0 ? <Star className="halfStar" /> : void 0}
{(function() {
var i, ref, ref1, results;
results = [];
for (emptyStar = i = ref = Math.ceil(rating), ref1 = maxStars; (ref <= ref1 ? i < ref1 : i > ref1); emptyStar = ref <= ref1 ? ++i : --i) {
results.push(<Star className="emptyStar" key={emptyStar} />);
}
return results;
})()}
</aside>;
};
.cjsx
file extension, but this is no longer necessary; regular .coffee
will do.