CoffeeScript - Postfix if and unless statements



Postfix if

You can rewrite the if-statement using the postfix form where, the statements that are to be executed are followed by the if along with the boolean expression.

Syntax

Following is the syntax of the postfix-if statement.

Statements to be executed if expression

Example

Given below is the example of the postfix if statement. Save the following example in a file with name postfix_if_example.coffee

name = "Ramu"
score = 60
console.log "Congratulations you have passed the examination" if score>40

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

c:\> coffee -c postfix_if_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("Congratulations you have passed the examination");
  }

}).call(this);

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

c:\> coffee postfix_if_example.coffee

On executing, the CoffeeScript file produces the following output.

Congratulations you have passed the exam

Postfix unless

You can rewrite the unless-statement using the postfix form where, the statements that are to be executed are followed by the unless along with the boolean expression.

Syntax

Following is the syntax of the postfix-if statement.

Statements to be executed unless expression

Example

Given below is the example of the postfix unless statement. Save the following example in a file with name postfix_unless_example.coffee

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

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

c:\> coffee -c postfix_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  postfix_unless_example.coffee

On executing, the CoffeeScript file produces the following output.

Sorry try again
coffeescript_conditionals.htm
Advertisements