Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

coffeescript

How to install CoffeeScript

Educative Answers Team

CoffeeScript is a language that compiles into JavaScript in such a way as to expose the good parts of JavaScript.

The code compiles one-to-one into the equivalent JS without interpretation at runtime. All existing libraries work from CoffeeScript – t​he output is readable and runs faster than the equivalent JS code.

svg viewer

Installation

Ensure that you have Node.js and npm installed by running:

node -v

Then, install CoffeeScript by running:

npm install --global- coffeescript

If you are using Coffeescript for a project, run:

npm install --save-dev coffeescript

You can run the coffee scripts using:

coffee -c

Usage

CoffeeScript allows user to easily write code in JavaScript. The following comparison shows how each command is written in each architecture:

# Assignment:
number   = 12
present = true

# Conditions:
number = -12 if present

# Functions:
square = (x) -> x * x

# Arrays:
list = [1, 2, 3, 4, 5]

# Objects:
math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x

# Splats:
race = (winner, runners...) ->
  print winner, runners

# Alert:
alert "Allowed" if present?

# Computing an Array 
cubes = (math.cube num for num in list)
// Assignment:
number = 12;
present = true;

// Conditions:
if (opposite) {
  number = -42;
}

// Functions:
square = function(x) {
  return x * x;
};

// Arrays:
list = [1, 2, 3, 4, 5];

// Objects:
math = {
  root: Math.sqrt,
  square: square,
  cube: function(x) {
    return x * square(x);
  }
};

// Splats:
race = function(winner, ...runners) {
  return print(winner, runners);
};

// Alert
if (present) {
  alert("Allowed");
}

// Computing an Array
cubes = (function() {
  results = [];
len = list.length;
  for (i = 0; i < len; i++) {
    num = list[i];
    results.push(math.cube(num));
  }
  return results;
})();

The following flags can be used to run commands for CoffeeScript:

svg viewer

The official documentation can be found here.

RELATED TAGS

coffeescript
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring