Skip to content

Conditionals

Bill Hails edited this page Jun 28, 2018 · 8 revisions

The conditional is if:

if (12 < 14) {
    20
} else {
    25
}

is 20.

Because of strict type checking the types of the two branches of the if must agree, and there must be an else branch.

we also have else if:

if (a < 14) {
    20
} else if (a < 16) {
    22
} else {
    25
}

but the above is just syntactic sugar and is rewritten internally to:

if (a < 14) {
    20
} else {
    if (a < 16) {
        22
    } else {
        25
    }
}

if can act as an expression as well as a statement. The following is valid:

x = if (y > 2) { y } else { z };

Note the semicolon is required to terminate expressions.

Up: Home

Next: Definition

Clone this wiki locally