Skip to main content

Control Blocks

If, elseif, and else

Value to bool conversion: false, null, undefined, 0, "", are false, all other values are true

let s = 100
if !s {
printf("s has a false value")
} elseif s > 100 {
printf("s is greater than 100")
} else {
printf("s is less than or greater to 100")
}

For Loop

For loop has the follwing strcutures:

  • for <index> <entry> = range <list> { }
  • for <key> <value> = range <map> { }
  • for range loop also apply to utf8 encoded string
    • in this case, the index of the loop is the starting position of the current rune, measured by bytes. see the example below
let lst = [0, 10, 20]
for i, v = range lst {
printf("index: %d: value: %d", i, v)
}

let map = `{x:0, y:10, z:20}`
for k, v = range map {
printf("key: %s: value: %d", k, v)
}

// apply for utf8 encoded string
let nihongo = "日本語"
for i, s = range nihongo {
printf("i:%d s:%s", i, s)
}
// i:0 s:日
// i:3 s:本
// i:6 s:語

for loop with three components: for init?; condition?; post? { }

let list = [0, 10, 20]
for let i = 0; i < len(list); i++ {
printf("index: %d: value: %d", i, list[i])
}

For loops can also be exited

break: break out of the current for loop

continue: skip the current iteration of the for loop

throw<error> : throw new Error("invalid data type")

try { } catch () {} finally {}

try {
nonExistentFunction();
} catch (e) {
printf("%s: %s", e.name, e.message);
// print out: ReferenceError: nonExistentFunction is not defined
} finally {
// execute after the try block and catch block(s) execute,
// but before the statements following the try...catch...finally block
}

Comments

Two styles of commenting is used.

  • single-line comments //
  • multi-line comments /* */
// This is a single line example

/*
This is how we can
do multi-line comments.
*/