Example

Choose a language, or say that you cannot

Run the language chooser over five candidate sets and see the three reasons it refuses: too little text, too little confidence, and a ranking that is too close to call.

Language detection returns a ranked list, and the chapter’s claim is that a ranked list is not an answer. The chooser takes the ranking and turns it into one of two things: a language, or a refusal with a reason. Refusing is a result, not a failure, and the reason is what makes it useful.

Run it

Save this as language.mjs and run it with Node 22 or later. No browser API: the chooser is a pure function over a candidate list and a string.

// Chapter 8: language detection is a decision, not an answer.

function chooseLanguage(candidates, text, {
  minimumConfidence = 0.8,
  minimumMargin = 0.2,
  minimumCharacters = 20
} = {}) {
  const [first, second] = candidates;
  const chars = [...text.trim()].length;

  if (!first || chars < minimumCharacters) {
    return { kind: "unknown", reason: "insufficient-text" };
  }

  if (first.confidence < minimumConfidence) {
    return { kind: "unknown", reason: "low-confidence" };
  }

  const margin = first.confidence - (second?.confidence ?? 0);
  if (margin < minimumMargin) {
    return { kind: "unknown", reason: "ambiguous-ranking" };
  }

  return {
    kind: "selected",
    language: first.detectedLanguage,
    confidence: first.confidence,
    margin
  };
}

const long = "This sentence is comfortably longer than the twenty character floor.";
const short = "too short";
const c = (lang, confidence) => ({ detectedLanguage: lang, confidence });

const cases = [
  { label: "clear winner", candidates: [c("en", 0.97), c("es", 0.31)], text: long },
  { label: "low confidence", candidates: [c("en", 0.61), c("fr", 0.30)], text: long },
  { label: "ambiguous ranking", candidates: [c("en", 0.86), c("nl", 0.79)], text: long },
  { label: "no candidates", candidates: [], text: long },
  { label: "too little text", candidates: [c("en", 0.99), c("de", 0.10)], text: short },
];

for (const testCase of cases) {
  const decision = chooseLanguage(testCase.candidates, testCase.text);
  const detail =
    decision.kind === "selected"
      ? `${decision.language} (${decision.confidence}, margin ${decision.margin.toFixed(2)})`
      : decision.reason;
  console.log(`${testCase.label.padEnd(20)} -> ${decision.kind.padEnd(9)} ${detail}`);
}

Expected outcome

clear winner         -> selected  en (0.97, margin 0.66)
low confidence       -> unknown   low-confidence
ambiguous ranking    -> unknown   ambiguous-ranking
no candidates        -> unknown   insufficient-text
too little text      -> unknown   insufficient-text

One case selects a language. Four refuse, each with a different reason, and two of the refusals are about the text rather than the candidates: a detector that is confident about a nine-character string has not established anything.

The margin is the part that is easy to skip. The clear winner’s top candidate is at 0.97 and the runner-up at 0.31, a margin of 0.66. The ambiguous case has a top candidate at 0.86 and a runner-up at 0.79: a margin of 0.07, under the 0.2 floor, and the answer would have been a coin flip between two languages.

The chooser

The chapter’s own function, in full:

function chooseLanguage(candidates, text, {
  minimumConfidence = 0.8,
  minimumMargin = 0.2,
  minimumCharacters = 20
} = {}) {
  const [first, second] = candidates;
  const chars = [...text.trim()].length;

  if (!first || chars < minimumCharacters) {
    return { kind: "unknown", reason: "insufficient-text" };
  }

  if (first.confidence < minimumConfidence) {
    return { kind: "unknown", reason: "low-confidence" };
  }

  const margin = first.confidence - (second?.confidence ?? 0);
  if (margin < minimumMargin) {
    return { kind: "unknown", reason: "ambiguous-ranking" };
  }

  return {
    kind: "selected",
    language: first.detectedLanguage,
    confidence: first.confidence,
    margin
  };

Three thresholds, and they fail in three different ways. The first is a length floor, the second a confidence floor, and the third a margin between the first and second candidate. Each refusal names which one it was, so the caller can ask for more text, ask for a better model, or accept that the text is genuinely ambiguous.

Mechanism and limitations

Documented: the thresholds, the meaning of each refusal and the function above are in the chapter’s own text, which also names the browser’s LanguageDetector as the source of the candidates and states that the real detection call is the part that needs the browser.

Observed: the run above. One case selected English with a margin of 0.66; the other four returned the reasons the chapter describes.

Not shown. The candidates here are constructed, so this exercises the decision the chapter owns and not the detector. The thresholds of 0.8, 0.2 and 20 characters are declared policy, and the chapter is explicit that they are choices, not properties of the text. A detector that never returns a second candidate would always clear the margin test, a property of the input rather than of the decision. Nothing here measures whether a refusal beats a guess for the reader.

Read the chapter .

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.