Mastering CoffeeScript: Understanding the basics and commenting techniques

CoffeeScript @ Training

CoffeeScript, a programming language that transcompiles into JavaScript, offers a more succinct and readable syntax compared to its counterpart. This article aims to provide a comprehensive understanding of the basic syntax of CoffeeScript and the methods of commenting within the language. CoffeeScript’s syntax is designed to be more readable and expressive than JavaScript, reducing the amount of boilerplate code required.

Basic Syntax of CoffeeScript

CoffeeScript’s syntax is designed to be minimalistic and clean, eliminating many of the braces and semicolons required in JavaScript. Here are some of the fundamental aspects of CoffeeScript syntax:

1. Variables and assignment

CoffeeScript does not use the var keyword for variable declarations. Variables are automatically local to the scope in which they are defined.


name = "Alice"

JavaScript equivalent:

var name = "Alice";

2. Functions

Functions are defined without the function keyword, and the return statement is implied.


greet = (name) -> "Hello, #{name}"

JavaScript Equivalent:

var greet = function(name) {
  return "Hello, " + name;

3. Loops and comprehensions

Loops in CoffeeScript are simpler and can be written in a single line.


alert(name) for name in ["Alice", "Bob", "Carol"]

JavaScript Equivalent:

for (var i = 0; i < names.length; i++) {

4. Conditional statements

Conditional statements in CoffeeScript can be written without parentheses and braces.


if temperature > 30
  alert "It's hot!"
  alert "It's not too hot."

JavaScript Equivalent:

if (temperature > 30) {
  alert("It's hot!");
} else {
  alert("It's not too hot.");

5. Classes and inheritance

CoffeeScript supports simple syntax for classes and inheritance.


class Animal
  constructor: (@name) ->
class Dog extends Animal
  bark: -> alert(@name + " says woof")

JavaScript equivalent:

var Animal = function(name) { = name;
var Dog = function(name) {, name);
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.bark = function() {
  alert( + " says woof");

Commenting in CoffeeScript

Comments are essential for explaining and documenting your code. CoffeeScript provides two types of comments:

1. Single-Line comments

Single-line comments start with a # and extend to the end of the line.


# This is a single-line comment

2. Block comments

Block comments are enclosed between ### and ###.


This is a block comment
covering multiple lines

Block comments in CoffeeScript can also be used to write multi-line JavaScript comments.

Author: user