CoffeeScript is a language that makes JavaScript easier to write and read. It simplifies JavaScript, making it readable and understandable, as well easier to maintain. CoffeeScript compiles into JavaScript
To install CoffeeScript, use the following command in your console.
npm install -g coffee-script
.. or you can download it from:
https://github.com/jashkenas/coffeescript
Variables
In CoffeeScript there are :
- No variable declarations
- No semicolons
Take a look at the following code snippet:
CoffeeScript
message = "Ready for some Coffee?"
alert(message)
This will compile into the following JavaScript file:
JavaScript
var message;
message = "Ready for some Coffee?";
alert(message);
There are 2 ways to create functions in JavaScript:
- Named Functions
function coffee() {
return confirm("Ready for some Coffee?");
}
- Function Expressions
var coffee = function() {
return confirm("Ready for some Coffee?");
}
In CoffeeScript, it's written with the following syntax:
[code] coffee();
But in CoffeeScript, we only use **Function Expressions.**
**CoffeeScript**
coffee = -> confirm "Ready for some Coffee?"
**JavaScript**
```js
var coffee = function() {
return confirm("Ready for some Coffee?");
}
1 tab or 2 spaces indented
-> converts to function() {
Always has a return value
Returning a String
The following highlighted expressions is similar to:
"Your answer is #{answer}"
CoffeeScript
coffee = ->
answer = confirm "Ready for some Coffee?"
"Your answer is " + answer
JavaScript
var coffee;
coffee = function() {
var answer;
answer = confirm("Ready for some Coffee?");
return "Your answer is " + answer;
}
Function Parameters
With CoffeeScript functions, you should use parenthesis on everything but the outermost call.
CoffeeScript
coffee = (message) ->
answer = confirm message
"Your answer is #{answer}"
alert coffee("Ready for some Coffee?")
Optinal Parameters
If we want a default message, we can assign it to the argument as below:
CoffeeScript
coffee = (message = "Ready for some Coffee?" ) ->
answer = confirm message
"Your answer is #{answer}"
JavaScript
var coffee;
coffee = function(message) {
var answer;
if (message == null) {
message = "Ready for some Coffee?";
}
answer = confirm(message);
return "Your answer is " + answer;
}
The CoffeeScript Compiler (optional)
You can optionally use a CoffeeScript Compiler to compile your code into JavaScript.
- Install Node.js
- Install npm
- Run
$ npm install -g coffee-script
Here are few Command-Line examples, you can use:
Creates test.js
coffee -c test.coffee
Every time test.coffee is updated re-compile.
coffee -cw test.coffee
Compile all .coffee files in the src dir into the js dir.
coffee -c src -o js
Every time a file is updated re-compile.
coffee -wc src -o js