Huffman Coding 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
- ✓Huffman Coding runs in O(n log n) time and O(n) space, in JavaScript as in every other language.
- ✓Neither the language nor Node's standard library has a priority queue. What exists is Array.prototype.sort, Array.prototype.splice and Map.
- ✓A comparator returns a number. Reviewers flag (a, b) => a.w > b.w immediately, because the boolean coerces to 1 or 0 and never to anything negative, so the engine is told every pair is already in order and nothing moves left.
- ✓The JavaScript trap: sort() called with no comparator is specified to convert each element to a string and compare UTF-16 code units.
- ✓V8 derives a hidden class from the order in which properties are added, so the snippet gives leaves and internal nodes the same five keys in the same order on purpose; the comparator's a.w load then stays monomorphic instead of degrading into a polymorphic inline cache.
What Huffman Coding actually is
Huffman Coding in JavaScript: what you actually reach for
JavaScript implementation
// Scan-code frequencies from one keyboard telemetry capture.
const counts = new Map([[0x1e, 412], [0x14, 388], [0x08, 351], [0x2c, 690],
[0x07, 140], [0x39, 140], [0x2a, 33], [0x4c, 2]]);
// Nothing in the language ships a priority queue, so this is three functions over one
// array. The comparator returns a NUMBER: a boolean coerces to 1/0, is never negative,
// and the array then simply never reorders.
const heap = [];
const cmp = (a, b) => a.w - b.w || a.seq - b.seq; // seq keeps ties deterministic
const swap = (i, j) => { const t = heap[i]; heap[i] = heap[j]; heap[j] = t; };
function push(node) {
heap.push(node);
for (let i = heap.length - 1; i > 0;) {
const p = (i - 1) >> 1;
if (cmp(heap[p], heap[i]) <= 0) break;
swap(p, i); i = p;
}
}
function pop() {
const top = heap[0], last = heap.pop();
if (heap.length === 0) return top;
heap[0] = last;
for (let i = 0;;) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < heap.length && cmp(heap[l], heap[m]) < 0) m = l;
if (r < heap.length && cmp(heap[r], heap[m]) < 0) m = r;
if (m === i) return top;
swap(m, i); i = m;
}
}
let seq = 0;
for (const [sym, w] of counts) push({ w, seq: seq++, sym, lo: null, hi: null });
while (heap.length > 1) {
const lo = pop(), hi = pop();
push({ w: lo.w + hi.w, seq: seq++, sym: null, lo, hi });
}
const depth = new Map();
(function walk(n, d) {
if (n.sym !== null) depth.set(n.sym, counts.size === 1 ? 1 : d);
else { walk(n.lo, d + 1); walk(n.hi, d + 1); }
})(heap[0], 0);
console.log([...depth].sort((x, y) => x[1] - y[1]).map(([s, d]) => s.toString(16) + ":" + d));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(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Huffman Coding?
Neither the language nor Node's standard library has a priority queue. What exists is Array.prototype.sort, Array.prototype.splice and Map. Map is the correct frequency table: object literals coerce every key to a string, expose __proto__, and reorder integer-like keys into ascending numeric position during enumeration, none of which you want in a symbol table. An off-the-shelf heap comes from npm, where heap-js and @datastructures-js/priority-queue are the usual choices. Written by hand the binary heap is about thirty lines, which is why most codebases just write it.
What is the most common JavaScript mistake when implementing Huffman Coding?
sort() called with no comparator is specified to convert each element to a string and compare UTF-16 code units. Applied to counts, [10, 9, 2, 140, 33] sorts to [10, 140, 2, 33, 9]. Nothing throws. The merge loop still draws two nodes each round, still builds a full binary tree, and still produces a legal prefix code, so every structural assertion passes and the tree is simply heavier than it should be. There is no runtime signal at all; the defect only appears when you compute the weighted path length and compare it against a second implementation, which is precisely the check nobody writes.
How does Huffman Coding actually perform in JavaScript?
V8 derives a hidden class from the order in which properties are added, so the snippet gives leaves and internal nodes the same five keys in the same order on purpose; the comparator's a.w load then stays monomorphic instead of degrading into a polymorphic inline cache. Numbers are IEEE-754 doubles and integer counts stay exact below 2^53, so summing weights up the tree never drifts. The heap is one contiguous array of pointers, each merge allocates exactly one object, and the transient nodes die in the young generation. Time complexity is O(n log n) and space is O(n).
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.