CoffeeScript - if-then...else statement
The if-then statement can be followed by an optional else statement, which executes when the Boolean expression is false. Using if-then...else statement, we can write the if...else statement in a single line.
Syntax
Following is the syntax of the if-then...else statement in CoffeeScript.
if expression then Statements (for true condition) else Statements (for false condition)
Example
Given below is the example of the if-then...else statement of CoffeeScript. Save this code in a file with name if_then_else_example.coffee
name = "Ramu" score = 30 if score>=40 then console.log "Congratulations" else console.log "Sorry try again"
Open the command prompt and compile the .coffee file as shown below.
c:\> coffee -c if_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 = 30;
if (score >= 40) {
console.log("Congratulations");
} else {
console.log("Sorry try again");
}
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as −
c:\> coffee if_then_else_example.coffee
On executing, the CoffeeScript file produces the following output.
Sorry try again
coffeescript_conditionals.htm
Advertisements