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 = range { }
  • for = range { }
  • 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 : 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.
*/

case(condition_1, value_1, [condition_2, value_2, …​], default_value)

evaluate a list of conditions and returns the first value whose condition is evaluated to true. If all conditions are false, the default value is returned

let i = 10  
case(i>10, "bigger than ten", i>=0, "positive", "negative") // return "positive"  
let i = -10  
case(i>10, "bigger than ten", i>=0, "positive", "negative") // return "negative"

template(text, variableMap)

Generates text output based on input variables. The template format is the same as Golang’s template. The variableMap is a map type holding variables or a json object.

let t = `Value of a: {{.fields.a}}
         List: {{.list}}`  
let opt = {"fields":{"a":"foo"}, "list": [1234, 5678]}  
let s = template(t, opt)  
//   Value of a: foo  
//   List: [1234 5678]