> For the complete documentation index, see [llms.txt](https://osl.mistium.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://osl.mistium.com/program-flow/while-and-until.md).

# While And Until

## While

* The `while` statement repeats a block of code while a condition is true.

### Example

```js
while boolean (
   command
   command
)
```

### Syntax

```js
while condition (
    commands
)
```

* `condition`: The condition that determines whether to continue executing the block of commands.
* `commands`: The commands to be executed within the loop.

### Example

```js
while distance_to_object < 10 (
    robot "moveForward" 10
    robot "turnLeft" 10

    robot "get_data"
    distance_to_object = robot."sensor1"
)
```

In this example, the robot will keep moving forward and turning left as long as there is an obstacle ahead.

## Until

* The `until` statement repeats a block of code until a condition is true.

### Example

```js
until boolean (
   command
   command
)
```

### Syntax

```js
until condition (
  commands
)
```

* `condition`: The condition that determines whether to stop executing the block of commands.
* `commands`: The commands to be executed within the loop.

### Example

```js
until isGoalReached (
  // do things to get to goal
)
```

In this example, the robot will keep moving forward until the goal is reached.

### Use Cases

1. **User Input Validation with `while`**

```js
// Ask for user input until a valid value is entered
userInput = null
while userInput != null (
  userInput = "hello".ask()
  // keep asking until the user answers
)
```

This example demonstrates how the `while` statement can be used to repeatedly prompt the user for input until a valid value is entered.

2. **Waiting for External Event with `until`**

```js
// Wait until a sensor detects an object
objectDetected = false
until objectDetected (
  robot "get_data"
  objectDetected = robot.detected
)
```

Here, the `until` statement is used to wait until a sensor detects an object before proceeding with the next set of commands.

## Incrementing Loop Counters

Counters can be incremented with the postfix `i++` / `i--` statements, or with assignment operators:

```js
i = 0
while i < 5 (
  log i
  i++         // postfix increment statement
)

// Equivalent forms
i += 1        // increment with assignment operator
i = i + 1     // explicit assignment
i--           // postfix decrement
```

Note that `++` between two values is the string concatenation operator (`a ++ b`); the postfix increment form only applies when `x++` stands alone as a statement.
