Trie Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Trie runs in O(m) time and O(n*m) space, in JavaScript as in every other language.
- ✓Nothing in the language or in Node core. You choose between three child containers and the choice is the design: a plain object literal {}, Object.create(null) (a null-prototype dictionary), or a Map.
- ✓A reviewer will reject children = {} on sight and ask for new Map() or Object.create(null).
- ✓The JavaScript trap: Two JavaScript-only bugs. First, with a plain object as children, the words 'constructor', 'toString' and '__proto__' break it: node.children['toString'] is truthy from Object.prototype, so has('toString') returns true for a trie that never saw the word, and assigning children['__proto__'] = child does not create a key at all, it reassigns the prototype.
- ✓V8 gives a plain object fast inline-cache property access only while its shape is stable; a trie node whose keys are added one at a time and deleted transitions to dictionary mode, and every subsequent lookup is a hash probe with none of the fast path.
What Trie actually is
Trie in JavaScript: what you actually reach for
JavaScript implementation
class TrieNode {
constructor() {
this.children = new Map(); // not {}: no prototype keys, no __proto__ trap
this.isWord = false;
}
}
export class Trie {
#root = new TrieNode();
insert(word) {
let node = this.#root;
for (const ch of word) { // code points, not UTF-16 units
let next = node.children.get(ch);
if (next === undefined) {
next = new TrieNode();
node.children.set(ch, next);
}
node = next;
}
node.isWord = true;
}
#walk(prefix) {
let node = this.#root;
for (const ch of prefix) {
node = node.children.get(ch);
if (node === undefined) return null;
}
return node;
}
has(word) {
const n = this.#walk(word);
return n !== null && n.isWord;
}
startsWith(prefix) {
return this.#walk(prefix) !== null;
}
*withPrefix(prefix) { // generator: a typeahead can stop at 10
const start = this.#walk(prefix);
if (start === null) return;
const stack = [[start, prefix]];
while (stack.length > 0) {
const [node, acc] = stack.pop();
if (node.isWord) yield acc;
for (const [ch, child] of node.children) stack.push([child, acc + ch]);
}
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Trie?
Nothing in the language or in Node core. You choose between three child containers and the choice is the design: a plain object literal {}, Object.create(null) (a null-prototype dictionary), or a Map. Map is the default recommendation because its keys are arbitrary strings with no prototype interference, it preserves insertion order, and .size is O(1). Node's require('node:util') and the WeakMap/Set family add nothing. On npm the survivors are trie-search and datastructures-js/trie; most production autocompletes just ship the twenty lines below.
What is the most common JavaScript mistake when implementing Trie?
Two JavaScript-only bugs. First, with a plain object as children, the words 'constructor', 'toString' and '__proto__' break it: node.children['toString'] is truthy from Object.prototype, so has('toString') returns true for a trie that never saw the word, and assigning children['__proto__'] = child does not create a key at all, it reassigns the prototype. Second, the character unit: for (const ch of word) iterates code points, but word[i] and charAt(i) iterate UTF-16 code units, so an emoji or any astral character is split into two lone surrogates and a trie built one way never matches a query built the other.
How does Trie actually perform in JavaScript?
V8 gives a plain object fast inline-cache property access only while its shape is stable; a trie node whose keys are added one at a time and deleted transitions to dictionary mode, and every subsequent lookup is a hash probe with none of the fast path. Map is hash-probing from the start, so it is slower on tiny fixed-shape nodes and considerably faster and more predictable on real branching. String concatenation while enumerating prefixes builds ropes rather than copying, so acc + ch in a DFS is cheap, but materialising a million results still forces flattening on the first read of each. Time complexity is O(m) and space is O(n*m).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.