Skip to content
Jing Lu edited this page May 15, 2013 · 13 revisions

See Language Specification.

if...else

syntax:

if (boolean-expression) expression-statement | block
[else expression-statement | block]

e.g.:

if (user_name == 'guest') quit();

or

if (user_name == 'admin') {
    var user = new User();
    user.role = 'admin';
}

Since the expression-statement in else could contains it...else self, so a if...else statement could be repeatedly used:

if (user_role == 'guest') {
    ...
} else if (user_role == 'admin') {
    ...
}

But an ambiguous statement as below is not recommended:

if (a < 5) 
  return 20;
else if (a < 10)           // not good sample
  return 30;
else 
  return 40;

Always use block instead of expression-statement is strongly recommended:

if (a < 5) {
  return 20;
} else if (a < 10) {       // good sample
  return 30;
} else {
  return 40;
}

for

for statement used to loop until condition is met. (boolean-expression to be true)

syntax:

for ( [local-]variable-declaration-list; boolean-expression; expression-statement-list ) 
    expression-statement | block

e.g.:

var total = 0;

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

console.log(total);

The result is:

45

One or more variables or expression-statements could be used in for statement:

for (var a = 0, b = 1; a < 10 && b < 10; a++, b++) {
    c = a + b;

for...in

for...in used to iterate over an object which could be enumerable. (supported by implements IEnumerable in .Net)

By default the following built-in types in ReoScript could be enumerable:

  • Array
  • Object
  • String

Iterate over array

var arr = [1,5,'ok',false];

for (element in arr) {
    console.log(element);
}

The result is:

1
5
ok
false

Iterate over object

var obj = {name: 'apple', color: 'red', amount: 5};

for (key in obj) {
    console.log(key + ': ' + obj[key]);
}

The result is:

name: apple
color: red
amount: 5

Iterate over string

var str = 'abc';

for (char in str) {
    console.log(char);
}

The result is:

a
b
c