unless-then...else statement



The unless-then statement can be followed by an optional else statement, which executes when the Boolean expression is true. Using unless-then...else statement, we can write the unless...else statement in a single line.

Syntax

Following is the syntax of the unless-then else statement in CoffeeScript.

unless expression then Statements (for false) else Statements (for true)

Example

Given below is the example of the unless-then else statement of CoffeeScript. Save the following example in a file with name unless_then_else_example.coffee

name = "Ramu"
score = 60
unless score>=40 then console.log "Sorry try again" else console.log "congratulations."

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

c:\> coffee -c unless_then_else_example.coffee

On compiling, it gives you the following JavaScript.

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

  name = "Ramu";

  score = 60;

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

}).call(this);

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

c:\> coffee unless_then_else_example.coffee

On executing, the CoffeeScript file produces the following output.

congratulations.
coffeescript_conditionals.htm
Advertisements