CoffeeScript Introduction

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 alternatively, you can download it from:

https://github.com/jashkenas/coffeescript

Variables

In CoffeeScript there are :

  1. No variable declarations
  2. 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:

  1. Named Functions
  2. 	function coffee() {
    		return confirm("Ready for some Coffee?");
    	}
    	
  3. Function Expressions
  4. 	var coffee = function() {
    		return confirm("Ready for some Coffee?");
    	}
    	

In CoffeeScript, it’s written with the following syntax:

coffee();

But in CoffeeScript, we only use Function Expressions.

CoffeeScript

coffee = ->
	confirm "Ready for some Coffee?"

JavaScript

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.

  1. Install Node.js
  2. Install npm
  3. 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

Be first to comment

Leave a Reply