Basics

Guides

API Reference

Menu

Basics

Guides

API Reference

Control Flow

Aussom has the four control-flow constructs you would expect: if/else, switch, while, and for. This page covers them all.

if / else if / else

if (x > 10) {
    c.log("big");
} else if (x > 0) {
    c.log("small but positive");
} else {
    c.log("zero or negative");
}

The condition is any expression that produces a truthy or falsy value:

Expression Truthy if
bool the value is true
int or double the value is non-zero
string the string is non-empty
null never truthy - always falsy
list always truthy (use #myList > 0 to check empty)
map always truthy (use #myMap > 0 to check empty)

For collections, prefer the explicit form. It reads better:

if (#items > 0) {
    c.log("we have items");
}

switch / case / default

switch works only on string values.

switch (action) {
    case "create": {
        c.log("creating ...");
    }
    case "update": {
        c.log("updating ...");
    }
    case "delete": {
        c.log("deleting ...");
    }
    default {
        c.log("unknown action: " + action);
    }
}

There is no break - cases do not fall through. Each case block runs to its closing brace and then switch ends.

while

A while loop checks its condition, then runs the body if the condition is true, then repeats.

i = 0;
while (i < 10) {
    c.log("i = " + i);
    i++;
}

Be careful with conditions that are always true:

while (true) {
    // infinite loop
}

while (1) {
    // also infinite - 1 is truthy
}

while (0) {
    // never runs - 0 is falsy
}

Use break to leave the loop early:

i = 0;
while (true) {
    if (i >= 5) {
        break;
    }
    i++;
}

for

There are three useful forms.

Classic counted loop

for (i = 0; i < 10; i++) {
    c.log(i);
}

The three parts are:

  1. Initialization, run once before the loop starts.
  2. Condition, checked before each iteration.
  3. Step, run after each iteration.

Any of the three can be omitted:

i = 0;
for (; i < 10; ) {
    // basically a while loop
    i++;
}

Iterating a list

When you give for a list, the loop variable receives each list item in turn.

items = [10, 20, 30];

for (n : items) {
    c.log(n);
}

Output:

10
20
30

Iterating a map

When you give for a map, the loop variable receives each key. You then look up the value yourself.

config = { host: "localhost", port: 8080, debug: true };

for (key : config) {
    c.log(key + " = " + config[key]);
}

Output (order is not guaranteed):

host = localhost
port = 8080
debug = true

break

break exits the nearest enclosing loop. It works in both while and for.

for (i = 0; i < 100; i++) {
    if (i == 5) {
        break;
    }
}

There is no continue keyword. To skip to the next iteration, wrap the body in an if and let the rest of the iteration be empty.

What to read next

  • Operators - every operator that can appear inside conditions and loop steps.
  • Functions - control flow inside function bodies, and how to return early.