Unscramble Labs

Build a Word Unscrambler in JavaScript

This guide builds a real, working word unscrambler from scratch, in plain JavaScript, explaining each step as it's added. Every snippet here was actually run against a real word list before being included on this page — not just written and assumed to work. For the theory behind why this approach is correct, see how anagram solvers work; this guide is the hands-on build.

Step 1: counting letters

The core idea behind rack-matching is simple: a word can be built from a rack if the rack contains at least as many of each letter as the word needs. To check that, both the word and the rack need to be turned into a count of each letter they contain, rather than compared character by character in order (order doesn't matter for this problem — "cat" and "act" use the same letters).

function countLetters(word) {
  const counts = {};
  for (const ch of word) counts[ch] = (counts[ch] || 0) + 1;
  return counts;
}

countLetters("stop") returns an object like { s: 1, t: 1, o: 1, p: 1 } — one count per distinct letter. This is the exact same idea as the 26-slot count vector described in how anagram solvers work, just stored as a plain object instead of a fixed-size array, which is simpler to write by hand and perfectly fine at the scale this guide is working at.

Step 2: checking whether a rack can build a word

With letters counted, checking containment is a direct comparison: for every letter the candidate word needs, does the rack have at least that many?

function canBuildFrom(word, rackCounts) {
  const need = countLetters(word);
  for (const letter in need) {
    if ((rackCounts[letter] || 0) < need[letter]) return false;
  }
  return true;
}

This correctly handles repeated letters, which is the detail that trips up a naive "does the rack contain each letter" check: a rack of "stop" contains one "o", so it can build "pot" (needs one "o") but not a made-up word needing two.

Step 3: searching a word list

Put the two pieces together and loop over an entire word list, keeping only the words that both fit within the rack's length and pass the containment check:

function findWords(rackLetters, wordList) {
  const rackCounts = countLetters(rackLetters.toLowerCase());
  const matches = [];
  for (const word of wordList) {
    if (word.length > rackLetters.length) continue;
    if (canBuildFrom(word, rackCounts)) matches.push(word);
  }
  return matches.sort((a, b) => b.length - a.length || a.localeCompare(b));
}

Tested against a small fixed list (["cat", "act", "cats", "tacs", "scat", "at", "ta", "dog", "stop", "pots", "tops", "pot"]) with the rack "cats", this returns exactly cats, scat, tacs, act, cat, at, ta — sorted longest first — and nothing else from the list, which is the correct, verified answer for that input.

Bonus: finding every anagram of one specific word

The same counting idea, applied slightly differently, answers a related question: given one word, which other words are exact anagrams of it (using every letter, nothing more or less)? Rather than counting letters and comparing counts, this is faster solved with the sorted-letter "signature" technique described in how anagram solvers work: sort a word's letters alphabetically, and any other word with the same sorted form is an exact anagram.

function signature(word) {
  return word.split("").sort().join("");
}

function findAnagramsOf(word, wordList) {
  const sig = signature(word.toLowerCase());
  return wordList.filter(w => w !== word.toLowerCase() && signature(w) === sig);
}

Run against the real 175,053-word list, findAnagramsOf("spare", words) returns exactly apers, apres, asper, pares, parse, pears, prase, presa, rapes, reaps and spear — 11 words, which together with "spare" itself makes the same 12-word A-E-P-R-S anagram set documented on words with the most anagrams. Both pages describe the same real data two different ways: that guide reports it as a fact about the dictionary, and this code reproduces it from scratch.

Loading the word list in the first place

Both functions above assume a wordList array already exists, but getting one is simple. In Node.js, reading this site's own word list is a single synchronous call: fs.readFileSync("words.v1.tsv", "utf8").split("\n").filter(Boolean).map(line => line.split("\t")[0]) — split into lines, drop any blank line, and take just the word column (this file's real format is tab-separated: word, tier, offensive-flag, region). The real file is about 2.7 MB for all 175,053 entries, small enough to load entirely into memory in well under a second and keep there for the life of the program, rather than re-reading it from disk on every search. In a browser, the equivalent is fetching the file as text and splitting it the same way; either environment, the findWords() and findAnagramsOf() functions above work completely unchanged once wordList is populated, since neither function cares where the array came from.

Common mistakes worth avoiding

A handful of bugs show up repeatedly in from-scratch implementations of this exact idea, all easy to avoid once named:

  • Forgetting to lowercase input before counting. "STOP" and "stop" produce different count-object keys ("S" versus "s") unless both the rack and every word in the list are normalized to the same case before comparison — this guide's findWords() lowercases the rack explicitly for this reason, and a real word list should be stored lowercase to begin with.
  • Getting the comparison direction backwards. The check is "does the rack have enough of this letter," not "does the word have enough of this letter" — reversing it (checking whether the word's count is at least the rack's count) silently returns the wrong answer for every word that doesn't use every rack letter, which is most of them.
  • Not handling non-letter characters. This guide's code assumes clean a-z input; a rack typed by a real user may contain spaces, punctuation, or accidental digits, which should be stripped or rejected before reaching countLetters() rather than silently counted as their own distinct "letters."
  • Re-deriving the rack's counts inside a loop. findWords() above correctly computes rackCounts once, outside the loop over the word list — computing it fresh for every single candidate word, inside the loop, would still produce correct results but would waste real work repeating the identical calculation thousands of times per search.

Step 4: running it against a real dictionary

A 12-word test list proves the logic works, but it doesn't prove the code is useful at real scale. Running the exact same findWords() function, unmodified, against this site's own 175,053-word list (data/words/words.v1.tsv) with the rack "stop" returns 16 words in 11 milliseconds: opts, post, pots, spot, stop, tops, opt, pot, sop, sot, top, ops, op, os, so, to. That's not a hypothetical result — it's the actual, measured output of running this guide's own code against the real file, and it matches this site's own production anagram solver exactly: querying "stop" through the live tool also returns precisely those same 16 words, confirming this simple, hand-written version and the site's production implementation agree on the right answer.

Step 5: why the real site doesn't stop here

Eleven milliseconds for one query against 175,053 words sounds fast, and for a one-off script, it is — this is a genuinely complete, correct unscrambler as written above. But it re-examines every single word in the list on every call, which becomes a real cost under sustained traffic (many searches per second, not one). How anagram solvers work covers what this site's actual production code adds on top of this same basic idea to stay fast at that scale: a quick bitmask pre-check (does the word need any letter the rack doesn't have at all, checked with a single bitwise operation) that eliminates most of the dictionary before the more detailed, per-letter count comparison ever runs, plus pre-grouping words by length so a search never has to look at words that are already too long to fit. Those are optimizations layered on top of exactly the same core logic built here — nothing about the underlying idea changes, only how much unnecessary work gets skipped before it.

Extending this: adding blank tiles

This version has no concept of a blank or wildcard tile. Adding basic support is a small, bounded change: instead of requiring the rack to have at least as many of every needed letter, allow a limited number of shortfalls (one per available blank) rather than rejecting the word outright.

function canBuildWithBlanks(word, rackCounts, blanks) {
  const need = countLetters(word);
  let shortfall = 0;
  for (const letter in need) {
    const missing = need[letter] - (rackCounts[letter] || 0);
    if (missing > 0) shortfall += missing;
  }
  return shortfall <= blanks;
}

Swapping canBuildFrom for canBuildWithBlanks (and passing a blanks count alongside the rack) is the entire change needed for basic blank-tile support — the same deficit-counting idea behind this site's own blank handling, described in more depth in how anagram solvers work.

Testing this before trusting it

Every function on this page was actually run, not just written and assumed correct, before being included here — the same standard this site holds its own guides and data pages to. Two checks matter most for code like this: a small, fully worked-out test case where the correct answer can be listed by hand and compared exactly, and a cross-check against an independent implementation of the same idea. findWords() was tested both ways: against the tiny fixed list in Step 3, where the output was compared character-for-character against a manually worked-out expected answer, and separately against the real 175,053-word dictionary with the rack "stop," where the result (16 words) was confirmed to exactly match this site's own production anagram solver for the identical query — two genuinely different implementations of the same underlying idea, agreeing on the same answer. That second kind of check matters more than it might seem: it's possible for buggy code to produce a plausible-looking, non-empty result that's still subtly wrong, and the only way to catch that is comparing against something else that's already known to be correct, rather than trusting that a result "looks reasonable."

Choosing a data structure for the word list

This guide stores the word list as a plain JavaScript array throughout, which is the right choice for the problem it's solving: findWords() has to examine every word's letters regardless of structure, since any word in the list could potentially match, so there's no shortcut a fancier structure would unlock for this specific operation. A Set would help with a different question — "is this exact word in the dictionary," answered in constant time regardless of list size — which is exactly what an anagram-checker-style exact-match lookup needs, but it wouldn't speed up scanning for every word that merely fits inside a rack, since a Set's speed comes from matching one specific string, not searching by letter content. This site's own production index (described in how anagram solvers work) uses yet another structure for a third reason: pre-grouping words by length, so a search for a 4-letter rack never has to examine a 9-letter word at all, cutting the search space before the letter-counting logic even runs. Picking a data structure is really about picking it to match the specific question being asked, not reaching for whichever one seems most sophisticated.

What this version doesn't do

This is a teaching implementation, not a drop-in replacement for a production tool, and it's worth being explicit about the gaps: it doesn't filter offensive words, doesn't distinguish US/UK spelling variants, doesn't support pattern wildcards like "c?t" or "st*ing", and re-scans the entire word list on every call rather than caching any work between queries. All of those are real, solvable problems — covered for this site's actual implementation in how anagram solvers work — but adding all of them at once would turn a short, readable tutorial into a much longer specification. Start with the working core above, and add exactly the pieces an actual project needs.

Related reading

For the theory behind why this approach is correct, and how this site's production version optimizes it further, see how anagram solvers work. To see the finished, optimized version in action rather than building it yourself, try the anagram solver directly. For the data this guide's own test run was measured against, see word list and sources.