Skip to content

Control Flow

cyxigo edited this page Jul 13, 2026 · 3 revisions

Introduction

Control flow is used to decide what blocks of code will execute and how many times.

Statements

Statement is a piece of code that does not produce any side expressions or values. All control flow constructs are statements. Also blocks and variable declarations via var (which we talked about in the very beginning) are statements themselves.

If

The simplest statement: if condition is truthy - execute a statement; if not - don't.

if (1 < 0) {
    print("Won't execute");
}

But we can also provide an else clause. If condition of if is not truthy, the else branch executes:

if (1 < 0) {
    print("Won't execute");
} else {
    print("This will execute");
}

You can also combine else with if, because both if and else expect a statement:

if (1 < 0) {
    print("Won't execute");
} else if (1 > 0) {
    print("This will execute");
} else {
    print("Won't execute");
}

You can create many branches with this.

While

The simplest looping statement: while condition is truthy, execute the statement.

var i = 0;

while (i < 10) {
    print(i);
    i = i + 1;
}

This will print:

0
1
2
3
4
5
6
7
8
9

For

The for statement is a looping statement which consists of three parts: an initializer, a condition and an increment.

Syntax:

for (initializer; condition; increment)

For example, our while example can be written as a for statement more gracefully:

for (var i = 0; i < 10; i = i + 1) {
    print(i);
}

Will print:

0
1
2
3
4
5
6
7
8
9
  • var i = 0; is the initializer
  • i < 10 is the condition
  • i = i + 1 is the increment.

You can use for to go through array elements:

var a = [1, 2, 3, 4];

for (var i = 0; i < a->count(); i = i + 1) {
    print(a[i]);
}

Will print:

1
2
3
4

Break

Sometimes you want to end the loop right from inside the loop itself. That's what break does:

for (var i = 0; i < 10; i = i + 1) {
    if (i == 4) {
        break;
    }

    print(i);
}

Will print only:

0
1
2
3

Continue

Sometimes you want to skip one iteration of the loop. That's what continue does:

for (var i = 0; i < 10; i = i + 1) {
    if (i == 4) {
        continue;
    }

    print(i);
}

Will print:

0
1
2
3
5
6
7
8
9

See? It didn't execute print(i); because we decided that if i is 4, we start a new iteration.

Next: Functions

Clone this wiki locally