CoffeeScript - Arithmetic Operators



CoffeeScript supports the following arithmetic operators. Assume variable A holds 10 and variable B holds 20, then −

Sr.No Operator and Description Example
1

+ (Addition)

Adds two operands

A + B = 30
2

− (Subtraction)

Subtracts the second operand from the first

A - B = -10
3

* (Multiplication)

Multiply both operands

A * B = 200
4

/ (Division)

Divide the numerator by the denominator

B / A = 2
5

% (Modulus)

Outputs the remainder of an integer division

B % A = 0
6

++ (Increment)

Increases an integer value by one

A++ = 11
7

-- (Decrement)

Decreases an integer value by one

A-- = 9

Example

The following example shows how to use arithmetic operators in CoffeeScript. Save this code in a file with name arithmetic_example.coffee

a = 33
b = 10
c = "test"
console.log "The value of a + b = is"
result = a + b
console.log result

result = a - b
console.log "The value of a - b = is "
console.log result

console.log "The value of a / b = is"
result = a / b
console.log result

console.log "The value of a % b = is"
result = a % b
console.log result

console.log "The value of a + b + c = is"
result = a + b + c
console.log result

a = ++a
console.log "The value of ++a = is"
result = ++a
console.log result

b = --b
console.log "The value of --b = is"
result = --b
console.log result

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c arithmetic_example.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var a, b, c, result;
  a = 33;
  b = 10;
  c = "test";

  console.log("The value of a + b = is");
  result = a + b;
  console.log(result);

  result = a - b;
  console.log("The value of a - b = is ");
  console.log(result);

  console.log("The value of a / b = is");
  result = a / b;
  console.log(result);

  console.log("The value of a % b = is");
  result = a % b;
  console.log(result);

  console.log("The value of a + b + c = is");
  result = a + b + c;
  console.log(result);

  a = ++a;
  console.log("The value of ++a = is");
  result = ++a;
  console.log(result);

  b = --b;
  console.log("The value of --b = is");
  result = --b;
  console.log(result);

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee arithmetic_example.coffee

On executing, the CoffeeScript file produces the following output.

The value of a + b = is
43
The value of a - b = is
23
The value of a / b = is
3.3
The value of a % b = is
3
The value of a + b + c = is
43test
The value of ++a = is
35
The value of --b = is
8
coffeescript_operators_and_aliases.htm
Advertisements