A code example should make its language, context, and important lines easy to find. This article develops a tiny statistics module while demonstrating code presentation and pseudocode. The examples are displayed as source; the public article does not execute them.

Copy the outer Markdown when you want the same presentation in your own article. Copy the rendered code when you want the program text itself.

Give a code block a useful filename

Put the language directly after the opening backticks. A title adds the filename to the compact toolbar, and {3-5} emphasizes the lines worth studying.

markdown
```typescript title="mean.ts" {3-5}
export function mean(values: readonly number[]): number {
if (values.length === 0) throw new Error('Expected a nonempty list.');
const total = values.reduce((sum, value) => sum + value, 0);
const count = values.length;
return total / count;
}
```
mean.tstypescript
export function mean(values: readonly number[]): number {
if (values.length === 0) throw new Error('Expected a nonempty list.');
const total = values.reduce((sum, value) => sum + value, 0);
const count = values.length;
return total / count;
}

The empty-list condition makes the contract explicit. For a production library, also decide how to handle nonfinite inputs and numerical precision. This sample focuses on small finite numbers.

Try it: use the code toolbar to copy the example, toggle wrapping, or download its source. Displayed line numbers are not part of the copied program.

Show what changed

Insertion, deletion, and text markers describe an edit without requiring a separate diff viewer.

markdown
```typescript title="minimum-count.ts" del={1} ins={2} mark="minimumCount"
const previousMinimum = 2;
const minimumCount = 3;
function ready(samples: readonly number[]): boolean {
return samples.length >= minimumCount;
}
```
minimum-count.tstypescript
const previousMinimum = 2;
const minimumCount = 3;
function ready(samples: readonly number[]): boolean {
return samples.length >= minimumCount;
}

These are presentation markers: a deleted-looking line still exists in the source and in a complete copy of the block. Edit the program itself when applying the change. Here the previous constant is unused, so the example remains valid source.

Connect files explicitly in Studio

Fences are independent by default. Give related JavaScript or TypeScript examples the same project value and different filename titles to create an article-local virtual project.

markdown
```typescript title="statistics.ts" project="sample-statistics"
export function average(values: readonly number[]): number {
if (!values.length) throw new Error('Expected a nonempty list.');
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
```
```typescript title="main.ts" project="sample-statistics"
import { average } from './statistics';
const readings = [2, 4, 6, 8];
console.log(average(readings)); // 5
```
statistics.tstypescript
export function average(values: readonly number[]): number {
if (!values.length) throw new Error('Expected a nonempty list.');
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
main.tstypescript
import { average } from './statistics';
const readings = [2, 4, 6, 8];
console.log(average(readings)); // 5

In the Studio source editor, completion, hover signatures, diagnostics, definition navigation, references, and rename can use these virtual files. F12 goes to a definition, Shift+F12 finds references, F2 renames, and Ctrl/Cmd+. opens available code actions. Those are editing features, not controls attached to the published reader's code blocks.

Virtual project names do not create files on disk. Relative imports can connect examples in the same article; external package declarations are not downloaded. If you copy the program into a real project, supply the corresponding files and build environment there.

For an intentionally incomplete exercise, check="off" suppresses Studio semantic diagnostics for that fence. It does not execute the example or repair its missing pieces.

Fold an implementation detail

Folding makes a longer example easier to scan while retaining its full source. A range is inclusive and uses the block's own source line numbers.

markdown
```typescript title="moving-mean.ts" project="sample-statistics" collapse={8-10}
import { average } from './statistics';
export function movingMean(values: readonly number[], windowSize: number): number[] {
if (!Number.isInteger(windowSize) || windowSize < 1) {
throw new Error('Window size must be a positive integer.');
}
const result: number[] = [];
for (let end = windowSize; end <= values.length; end++) {
result.push(average(values.slice(end - windowSize, end)));
}
return result;
}
```
moving-mean.tstypescript
import { average } from './statistics';
export function movingMean(values: readonly number[], windowSize: number): number[] {
if (!Number.isInteger(windowSize) || windowSize < 1) {
throw new Error('Window size must be a positive integer.');
}
const result: number[] = [];
3 collapsed lines
for (let end = windowSize; end <= values.length; end++) {
result.push(average(values.slice(end - windowSize, end)));
}
return result;
}

Try it: expand the folded loop, then copy the block. The complete implementation is retained even when the loop is folded. The example returns complete trailing windows only; a list shorter than the window produces an empty result.

Wrap long lines without changing the source

Use wrap for a configuration line that should fit the available reading width. Visual wrapping never inserts newlines into the copied string.

markdown
```json title="display.json" wrap
{"description":"A deliberately long configuration description that remains one source line while the reader can view it comfortably inside a narrow article column.","showLegend":true}
```
display.jsonjson
{"description":"A deliberately long configuration description that remains one source line while the reader can view it comfortably inside a narrow article column.","showLegend":true}

For a very short command or output, showLineNumbers=false removes unnecessary numbering.

Label terminal examples clearly

A terminal frame tells the reader that the block contains a command rather than a source file. This command validates this sample from the Glass project root; it is shown here without being run by the article.

markdown
```bash title="Terminal" frame="terminal" showLineNumbers=false
npm run markdown:check -- content/lab/sample-code-and-algorithms.md --json
```
Terminalbash
npm run markdown:check -- content/lab/sample-code-and-algorithms.md --json

Keep actual output separate from commands when the distinction matters. Do not present fabricated benchmark output as a measurement.

Explain an algorithm in academic form

Pseudocode lets the structure of an algorithm take priority over a programming language's syntax. The default academic style supports inline math. An enclosing algorithm provides a numbered label and cross-reference.

markdown
:::algorithm[Mean of a nonempty list]{#alg-average}
```pseudocode title="Mean of a list"
INPUT values with $n>0$ elements
total ← $0$
FOR EACH value IN values DO
total ← total + value
END FOR
RETURN $\frac{\text{total}}{n}$
```
:::
Refer to :ref[alg-average] from the explanation.

Algorithm 1 · Mean of a nonempty list

Mean of a listpseudocode
INPUT values with elements
total ←
FOR EACH value IN values DO
total ← total + value
END FOR
RETURN

Algorithm 1 keeps the nonempty-input assumption visible. Each value contributes once, so the algorithm uses a number of additions proportional to the input length and a constant amount of extra storage, apart from the input itself.

Prefer code-style pseudocode for implementation notes

The same language accepts style="code". Its monospace presentation retains any $...$ notation literally rather than turning it into inline math.

markdown
```pseudocode title="average.pseudo" style="code" showLineNumbers=false
FUNCTION average(values)
REQUIRE length(values) > 0
total := 0
FOR EACH value IN values DO
total := total + value
END FOR
RETURN total / length(values)
END FUNCTION
```
average.pseudopseudocode
FUNCTION average(values)
REQUIRE length(values) > 0
total := 0
FOR EACH value IN values DO
total := total + value
END FOR
RETURN total / length(values)
END FUNCTION

Pseudocode is explanatory notation. It is not a runnable language, and the renderer does not verify the algorithm's correctness. State assumptions and check the reasoning just as you would for a prose description.

A small publishing checklist

  • Choose a supported language and a descriptive filename.
  • Explain the important line in the surrounding prose.
  • Keep related virtual filenames unique within each project.
  • Check copied source, not only the highlighted appearance.
  • Use folds and wrapping to improve reading without hiding essential assumptions.

If the code needs an argument or a diagram around it, keep that explanation in the article instead of placing every sentence in another code block.