Control flow
Conditions always go in parentheses: if (x > 0), never if x > 0.
if and else
ts
const hp: int = 12;
if (hp <= 0) {
console.log("defeated");
} else if (hp < 20) {
console.log("hurt");
} else {
console.log("healthy");
}
const label: string = hp > 50 ? "strong" : "weak";
console.log(label);Looping over a collection: for...of
ts
const party: Array<string> = ["Ada", "Brin", "Cass"];
for (const name of party) {
console.log(name);
}for...of is the loop to reach for. It works on arrays, maps, sets and strings.
One way to loop
The language also accepts a foreach keyword as an alias. Don't use it. The style guide allows only for...of, and every sample on this site follows it.
Counting loops
ts
let total: int = 0;
for (let i: int = 1; i <= 10; i++) {
total += i;
}
console.log(total); // 55Each iteration gets a fresh i, so closures made inside the loop each see their own value.
Ranges
a..b includes both ends. a..<b leaves out the end. Loop over a range with for...in or for...of; both count the same values:
ts
for (const i in 0..3) {
console.log(i); // 0, 1, 2, 3
}
for (const i in 0..<3) {
console.log(i); // 0, 1, 2
}A range is also a value: an array of the same numbers, so you can store it, pass it or spread it.
ts
const steps: int[] = 0..<3; // [0, 1, 2]
const padded: int[] = [9, ...(1..2)]; // [9, 1, 2]Object keys
for...in over an object gives you its keys:
ts
const stats: Object = { str: 5, dex: 7 };
for (const key in stats) {
console.log(key);
}while and do...while
ts
let n: int = 3;
while (n > 0) {
console.log(n);
n--;
}
let tries: int = 0;
do {
tries++;
} while (tries < 3);
console.log(tries);switch
Each branch needs case and usually a break. Without break, a case falls through to the next one.
ts
function weekday(day: int): string {
switch (day) {
case 0:
return "Sunday";
case 6:
return "Saturday";
default:
return "a weekday";
}
}
console.log(weekday(6));For enums, switch strict checks that every member is covered, and switch bitflag matches flags. See Enums.
break, continue and labels
ts
for (let i: int = 0; i < 10; i++) {
if (i == 5) {
break;
}
if (i % 2 == 0) {
continue;
}
console.log(i); // 1, 3
}
outer: for (let row: int = 0; row < 3; row++) {
for (let col: int = 0; col < 3; col++) {
if (row + col > 2) {
break outer;
}
}
}Labels can only go on loops.
Running code on the way out: defer
defer runs a statement when the current scope ends, however it ends. See Errors.