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

Search Engine Implementation in JavaScript

19 min readadvanced
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

  • ✓Search Engine runs in O(n log n) time and O(n) space, in JavaScript as in every other language.
  • ✓Map<string, Map<number, number>> is the right container -- a plain object coerces every key to a string and reorders integer-like ones.
  • ✓Reviewers reject arr.sort() with no comparator and reject {} as a term map. They want Map and Set, `??` rather than `||` when a term frequency can legitimately be 0, and true private #fields on the index class instead of an underscore convention.
  • ✓The JavaScript trap: Array.prototype.sort with no comparator converts every element to a string and compares UTF-16 code units.
  • ✓V8 caches a string's hash on the string object, so repeated Map lookups of the same token do not rehash -- token reuse is nearly free, novel tokens are not.

What Search Engine actually is

A search engine is an inverted index plus a ranker. Indexing tokenizes each document, normalizes the tokens, and appends (docId, termFrequency) to a postings list per term; building or merging those sorted runs is the O(n log n). Querying pulls one postings list per query term, intersects or unions them, scores each candidate with something like BM25, and keeps the top k in a bounded heap. You reach for it the moment LIKE '%x%' stops finishing and users start expecting relevance, not just matches.

Search Engine in JavaScript: what you actually reach for

Map<string, Map<number, number>> is the right container -- a plain object coerces every key to a string and reorders integer-like ones. Intl.Segmenter with {granularity: 'word'} does real word segmentation including CJK, and every segment carries an isWordLike flag that a /\w+/ regex cannot give you. String.prototype.normalize('NFKC') folds full-width and compatibility forms before you lowercase. The platform ships no stemmer and no BM25: lunr, minisearch and flexsearch are the ecosystem answers, and SQLite FTS5 through better-sqlite3 once the index leaves memory.

JavaScript implementation

Reviewers reject arr.sort() with no comparator and reject {} as a term map. They want Map and Set, `??` rather than `||` when a term frequency can legitimately be 0, and true private #fields on the index class instead of an underscore convention. Iterating a Map with for..of destructuring beats Object.entries. A corpus is walked with an async generator, never with an array of promises the size of the corpus.
javascript
const seg = new Intl.Segmenter("en", { granularity: "word" });

function tokens(text) {
  const out = [];
  for (const s of seg.segment(text.normalize("NFKC")))
    if (s.isWordLike) out.push(s.segment.toLowerCase());
  return out;
}

export class InvertedIndex {
  #postings = new Map();   // term -> Map(docId -> tf)
  #len = new Map();

  add(docId, text) {
    const t = tokens(text);
    this.#len.set(docId, t.length);
    for (const term of t) {
      let m = this.#postings.get(term);
      if (m === undefined) this.#postings.set(term, (m = new Map()));
      m.set(docId, (m.get(docId) ?? 0) + 1);
    }
  }

  search(query, k = 10) {
    const N = this.#len.size, scores = new Map();
    for (const term of tokens(query)) {
      const m = this.#postings.get(term);
      if (m === undefined) continue;
      const idf = Math.log(1 + (N - m.size + 0.5) / (m.size + 0.5));
      for (const [doc, tf] of m)
        scores.set(doc, (scores.get(doc) ?? 0) + (idf * tf) / (tf + 1.2));
    }
    // numeric comparator is mandatory: bare sort() compares stringified values
    return [...scores].sort((a, b) => b[1] - a[1]).slice(0, k);
  }
}

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

Array.prototype.sort with no comparator converts every element to a string and compares UTF-16 code units. A postings list sorted as [2, 10, 9] comes back [10, 2, 9], and a galloping intersection that assumes ascending numeric doc ids then returns the wrong document set -- no exception, just plausible-looking wrong results that pass on a ten-document fixture. Always pass (a, b) => a - b. The sibling trap: a plain object used as postings reorders integer-like keys into ascending numeric order regardless of insertion order, so Object.keys() is not your term order and never was.

Performance in JavaScript, beyond the O(n log n)

V8 caches a string's hash on the string object, so repeated Map lookups of the same token do not rehash -- token reuse is nearly free, novel tokens are not. Strings are UTF-16, so .length counts code units and an emoji costs 2; budget index memory on code units, not characters. Postings held in an Int32Array instead of Array<number> drop from an 8-byte tagged slot per element to 4 bytes and lose the elements-kind transition risk entirely, roughly halving resident size. Sorting pays one JS call per comparison, and the gap is not just a constant factor: a full sort is O(n log n) while a bounded k-sized heap is O(n log k) -- at a million candidates and k = 10 that is roughly 20 comparisons per candidate against 3. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Search Engine between languages.

Real-World Applications

Search Engine 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 Search Engine helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Search Engine appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Search Engine 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 Search Engine 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 Search Engine?

Map<string, Map<number, number>> is the right container -- a plain object coerces every key to a string and reorders integer-like ones. Intl.Segmenter with {granularity: 'word'} does real word segmentation including CJK, and every segment carries an isWordLike flag that a /\w+/ regex cannot give you. String.prototype.normalize('NFKC') folds full-width and compatibility forms before you lowercase. The platform ships no stemmer and no BM25: lunr, minisearch and flexsearch are the ecosystem answers, and SQLite FTS5 through better-sqlite3 once the index leaves memory.

What is the most common JavaScript mistake when implementing Search Engine?

Array.prototype.sort with no comparator converts every element to a string and compares UTF-16 code units. A postings list sorted as [2, 10, 9] comes back [10, 2, 9], and a galloping intersection that assumes ascending numeric doc ids then returns the wrong document set -- no exception, just plausible-looking wrong results that pass on a ten-document fixture. Always pass (a, b) => a - b. The sibling trap: a plain object used as postings reorders integer-like keys into ascending numeric order regardless of insertion order, so Object.keys() is not your term order and never was.

How does Search Engine actually perform in JavaScript?

V8 caches a string's hash on the string object, so repeated Map lookups of the same token do not rehash -- token reuse is nearly free, novel tokens are not. Strings are UTF-16, so .length counts code units and an emoji costs 2; budget index memory on code units, not characters. Postings held in an Int32Array instead of Array<number> drop from an 8-byte tagged slot per element to 4 bytes and lose the elements-kind transition risk entirely, roughly halving resident size. Sorting pays one JS call per comparison, and the gap is not just a constant factor: a full sort is O(n log n) while a bounded k-sized heap is O(n log k) -- at a million candidates and k = 10 that is roughly 20 comparisons per candidate against 3. Time complexity is O(n log n) and space is O(n).

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

If you are a student, see what Devin offers students for free 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.