CoffeeScript - unless statement



The unless statement is an additional feature provided by CoffeeScript. It is exactly opposite to the if statement. The code in the unless block will be executed if the given condition is false.

Syntax

Given below is the syntax of the unless statement in CoffeeScript. Just like if statement, it contains an unless keyword, a Boolean expression, and a block of code which will be executed if the given expression is false.

unless expression
   Statement(s) to be executed if the expression is false

Flow Diagram

Unless Statement

Example

The following example demonstrates the usage of unless statement in CoffeeScript. Save this code in a file with the name unless_example.coffee

name = "Ramu"
score = 30
unless score>=40
  console.log "Sorry try again"

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

c:\> coffee -c unless_example.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var name, score;

  name = "Ramu";

  score = 30;

  if (!(score >= 40)) {
    console.log("Sorry try again");
  }

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as −

c:\> coffee unless_example.coffee

On executing, the CoffeeScript file produces the following output.

Sorry try again
coffeescript_conditionals.htm
Advertisements