Control Flow

Change Topic
  • Conditional statements
  • Ternary Operator or Select
  • Switch / Case
  • Loop Over - Iterables
  • Loop Conditional Exit
  • Co-Routine - Yield
  • Exceptions

Select Language

TypeScript Control-Flow


Conditional

function checkNumber(num: number): string { if (num > 0) { return "Positive"; } else if (num < 0) { return "Negative"; } else { return "Zero"; } }

Ternary and Select Expressions

Ternary operator:

const result = num > 0 ? "Positive" : num < 0 ? "Negative" : "Zero";

Loop Over

TypeScript supports multiple loop constructs.

Basic for loop:

for (let i = 0; i < 5; i++) { console.log(i); }

for...of (iterates over iterable objects):

const numbers: number[] = [1, 2, 3]; for (const num of numbers) { console.log(num); }

for...in (iterates over object keys):

const user = { id: 1, name: "Alice" }; for (const key in user) { console.log(`${key}: ${user[key as keyof typeof user]}`); }

Loop Conditional Exit

TypeScript allows breaking out of loops based on conditions and also supports do...while loops, which execute at least once before checking the condition.

Basic do...while loop:

do { console.log("Executing at least once"); } while (false);

do...while with condition:

let i = 0; do { console.log(i); i++; } while (i < 5); ``` breaking out of loops based on conditions. ```typescript for (let i = 0; i < 10; i++) { if (i === 5) { break; // Exit loop when i equals 5 } console.log(i); }

Using continue to skip iterations:

for (let i = 0; i < 10; i++) { if (i % 2 === 0) { continue; // Skip even numbers } console.log(i); }

Coroutine and Yield

TypeScript does not support native coroutines or yield, but it supports generator functions which behave similarly.

Generator function with yield:

function* numberGenerator(): Generator<number> { yield 1; yield 2; yield 3; } const gen = numberGenerator(); console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3

Using yield in a loop:

function* infiniteCounter(): Generator<number> { let i = 0; while (true) { yield i++; } } const counter = infiniteCounter(); console.log(counter.next().value); // 0 console.log(counter.next().value); // 1 console.log(counter.next().value); // 2

Generators provide a way to implement lazy iteration, similar to coroutines in other languages.