CoffeeScript - if...else statement

The if statement executes the given block of code if the specified Boolean expression is true. What if the Boolean expression is false?

The 'if...else' statement is the next form of control statement that allows CoffeeScript to execute statements in a more controlled way. It will have an else block which executes when the Boolean expression is false.


Given below is the syntax of the if-else statement in CoffeeScript. If the given expression is true, then the statements in the if block are executed and if it is false the statements in the else block are executed.

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

Flow Diagram

if else statement


The following example demonstrates how to use the if-else statement in CoffeeScript. Save this code in a file with name

name = "Ramu"
score = 30
if score>=40
  console.log "Congratulations have passed the examination"
  console.log "Sorry try again"

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

c:\> coffee -c

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 have passed the examination");
  } else {
    console.log("Sorry try again");


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

c:\> coffee

On executing, the CoffeeScript file produces the following output.

Sorry try again
Kickstart Your Career

Get certified by completing the course

Get Started