CoffeeScript - The until variant of while



The until alternative provided by the CoffeeScript is exactly opposite to the while loop. It contains a Boolean expression and a block of code. The code block of the until loop is executed as long as the given Boolean expression is false.

Syntax

Given below is the syntax of the until loop in CoffeeScript.

until expression
   statements to be executed if the given condition Is false

Example

The following example demonstrates the usage of until loop in CoffeeScript. Save this code in a file with name until_loop_example.coffee

console.log "Starting Loop "
count = 0  
until count > 10
   console.log "Current Count : " + count
   count++;
   
console.log "Set the variable to different value and then try"

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

c:\> coffee -c until_loop_example.coffee

On compiling, it gives you the following JavaScript. Here you can observe that the until loop is converted into while not in the resultant JavaScript code.

// Generated by CoffeeScript 1.10.0
(function() {
  var count;

  console.log("Starting Loop ");

  count = 0;

  while (!(count > 10)) {
    console.log("Current Count : " + count);
    count++;
  }

  console.log("Set the variable to different value and then try");

}).call(this);

Now, open the command prompt again and run the Coffee Script file as shown below.

c:\> coffee until_loop_example.coffee

On executing, the CoffeeScript file produces the following output.

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Set the variable to different value and then try 
coffeescript_loops.htm
Advertisements