Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Trie Implementation in JavaScript

14 min readintermediate
Website QA and SEO audits

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

A trie (prefix tree) stores string keys as paths of single-symbol edges: the key lives in the walk from the root, not in any one node, and every node marks whether a key ends there. Lookup, insert and delete are O(m) in the key length with no hashing of the whole key and no collisions. Engineers reach for it when the query is prefix-shaped rather than exact: autocomplete and typeahead, longest-prefix-match routing tables, dictionary/word-break checks, IP and URL prefix rules, and streaming multi-pattern search (Aho-Corasick is a trie plus failure links). A hash map beats it for pure exact lookup; the trie wins the moment you need 'all keys starting with X' or ordered traversal.

Trie in JavaScript: what you actually reach for

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.

JavaScript implementation

A reviewer will reject children = {} on sight and ask for new Map() or Object.create(null). They expect the walk helper to be shared by has(), startsWith() and the enumeration path instead of three copy-pasted loops, prefix enumeration to be a generator function* so a typeahead can stop after ten results, and node fields to be initialised in the constructor rather than added later. #private class fields are preferred over an underscore convention for the root.
javascript
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 Free

The JavaScript-specific 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. 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.

Performance in JavaScript, beyond the O(m)

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. The asymptotic cost is the same in every language, O(m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Trie between languages.

Real-World Applications

Trie applies wherever its problem shape appears in your own code. In JavaScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Trie helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Trie appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Trie over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Trie to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.