CoffeeScript - Logical operators



CoffeeScript supports the following logical operators. Assume variable A holds true and variable B holds false, then −

Sr.No Operator and Description Example
1

&& (Logical AND)

If both the operands are true, then the condition becomes true.

(A && B) is false.
2

|| (Logical OR)

If any of the two operands is true, then the condition becomes true.

(A || B) is true.
3

! (Logical NOT)

Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false.

! (A && B) is true.

Example

Following is the example demonstrating the use of logical operators in coffeeScript. Save this code in a file with name logical_example.coffee.

a = true
b = false

console.log "The result of (a && b) is "
result = a && b
console.log result

console.log "The result of (a || b) is "
result = a || b
console.log result

console.log "The result of !(a && b) is "
result = !(a && b)
console.log result

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

c:\> coffee -c logical_example.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var a, b, result;
  a = true;
  b = false;

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

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

  console.log("The result of !(a && b) is ");
  result = !(a && b);
  console.log(result);

}).call(this);

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

c:\> coffee logical_example.coffee

On executing, the CoffeeScript file produces the following output.

The result of (a && b) is
false
The result of (a || b) is
true
The result of !(a && b) is
true
coffeescript_operators_and_aliases.htm
Advertisements