---
title: "Control flow, TypeShade authoring guide"
description: "After this page you can branch, loop and dispatch inside a shader body…"
url: https://typeshade.dev/guide/internals/control-flow/
language: en
---

# Control flow

After this page you can branch, loop and dispatch inside a shader body, and you can tell a statement that picks what to do from an expression that picks a value. Each form is TypeScript’s own, and each emits the WGSL and GLSL statement of the same shape.

## if, else if and else

`if` takes a [`bool`](https://typeshade.dev/reference/types/bool/). There is no truthiness: `if (n)` on a number is refused, so write the comparison, `if (n != 0)`.

```ts
if (idx == 1) {
  pos = vec2(3., -1.);
} else if (idx == 2) {
  pos = vec2(-1., 3.);
} else {
  pos = vec2(-1., -1.);
}
```

`!` is logical negation, so a guard on the false case reads `if (!hit)`.

## for and while

A `for` means what it means in TypeScript. The compiler records it as a counted loop when it has an integer counter, a constant step, and an exit that compares the counter to a bound the body does not write. The bound may be a value the program learns at run time, a uniform, a parameter or a storage array’s `.length`. Any other `for` is an open loop, as a `while` is.

```ts
let acc = 0.;
for (let i: u32 = 0; i < 64; i++) {
  acc += f32(i);
}
```

The counter needs no annotation when its start is a non-negative literal and the bound is a [`u32`](https://typeshade.dev/reference/types/u32/); otherwise it is an [`i32`](https://typeshade.dev/reference/types/i32/). When the start, the bound and the step are constants, a step that moves the counter away from its bound is refused with [`TS8007`](https://typeshade.dev/reference/errors/ts8007/), because the loop would not exit. `while (cond)` is the open loop, for a loop with no counter.

```ts
let n: u32 = start;
let steps: u32 = 0;
while (n != 1) {
  n = select(n / 2, 3 * n + 1, (n & 1) == 1);
  steps++;
}
```

`docs/use-typeshade-surface.md` §17 has every loop header the compiler takes, and why it refuses the rest.

## Break, continue and discard

Three statements end a piece of work early. `break` exits the nearest enclosing loop, or the current switch case. `continue` skips to the next iteration of the nearest enclosing loop. `discard` kills the current fragment invocation with no colour or depth write, and belongs in a fragment stage.

```ts
"use typeshade";

declare const dists: storage<array<f32>>;

@fragment
export function fs(alpha: location<0, f32>, count: location<1, u32, { interpolate: "flat" }>): vec4 {
  let nearest = 1e10;
  for (let i: u32 = 0; i < count; i++) {
    const d = dists[i];
    if (d < 0.) {
      continue; // no distance recorded, next iteration
    }
    if (d < 0.001) {
      break; // close enough, leave the loop
    }
    nearest = min(nearest, d);
  }
  if (alpha < 0.01) {
    discard;
  }
  return vec4(nearest, 0., 0., alpha);
}
```

`discard` is allowed in a fragment entry, and in a helper as long as no vertex or compute entry can reach it: the check closes over the call graph, and a refusal names the helper and the entry.

## Switch

`switch` dispatches on a single integer value, the *scrutinee*, which is an `i32` or a `u32`. Each `case` label is a constant, and `default` is the optional fall-through arm. It lowers to a real `switch` on both targets.

```ts
let radiusPx = rawRadius;
switch (sizeMode) {
  case 1:
    radiusPx = rawRadius / viewport.z;
    break;
  case 2:
    radiusPx = rawRadius * dpr;
    break;
  default:
    break;
}
```

A case ends in `break` or `return`. WGSL has no fall-through, so a case that runs into the next one is refused with the remedy.

## Choosing a value

The ternary `c ? a : b` picks a value by a condition. It is WGSL’s [`select`](https://typeshade.dev/reference/functions/select/), so both arms are evaluated and one is chosen, which suits a pair of cheap values:

```ts
const dir = segLen < 1e-6 ? vec2(1., 0.) : segVec / segLen;
```

When an arm is expensive, or a chain of conditions picks among several values, declare the variable and assign it in an `if` chain, so the GPU runs only the arm it takes:

```ts
let clip: vec4;
if (projParams.x < 0.5) {
  clip = mvp * vec4(rel2d, 0., 1.);
} else if (projParams.x < 6.5) {
  clip = mvp * vec4(relG, 0., 1.);
} else {
  clip = mvp * vec4(ecefRtc, 1.);
}
```

## Folding a loop with reduce

An *accumulator* is a value carried from one iteration of a loop to the next. An array’s [`reduce`](https://typeshade.dev/api/reduce/) carries one for you: `xs.reduce(f, init)` runs `acc = f(acc, value, index)` from `init`, left to right, as TypeScript runs it.

```ts
"use typeshade";

export function nearestOf(p: vec2, pts: array<vec2, 8>): f32 {
  return pts.reduce((acc, q) => min(acc, length(p - q)), 1e10);
}
```

The call emits the loop and the variable it updates, the same code as writing `let` plus `for` plus the assignment yourself. `map`, `forEach`, `some` and `every` are there too, and all but `map` work on a runtime-sized storage array (`docs/use-typeshade-surface.md` §63).

## Dispatch on an enum

A numeric `enum` declares a set of named integer constants, and each member is a module constant, so a member can stand in a `case` label:

```ts
"use typeshade";

enum Kind {
  Line,
  Fill,
  Stroke,
}

export function colorOf(kind: i32, line: vec4, fill: vec4, stroke: vec4): vec4 {
  switch (kind) {
    case Kind.Line:
      return line;
    case Kind.Fill:
      return fill;
    default:
      return stroke;
  }
}
```

`Kind.Fill` reads the constant, `1`, and the enum’s name as a type is `i32`. A member the enum does not declare is an error where it is read. A string member is refused, because no GPU type holds one.

## Early returns

A `return` inside a branch or a loop leaves the function, as it does in TypeScript:

```ts
"use typeshade";

export function sign01(winding: i32, minDist: f32): f32 {
  if (winding != 0) {
    return 1. - minDist;
  }
  return 1. + minDist;
}
```

A function that returns a value must return one on every path. A path that falls off the end of a value-returning function is an error at compile.
