Circular Buffer 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
- ✓Circular Buffer runs in O(1) time and O(n) space, in JavaScript as in every other language.
- ✓Nothing in the language ships a ring buffer. The contiguous option is a TypedArray over an ArrayBuffer (Float64Array, Int32Array, Uint8Array), which stores raw values with no per-element object header.
- ✓Reviewers reject shift and unshift on the hot path, and reject delete buf[i] outright: it punches a hole and drops the array out of packed elements kind.
- ✓The JavaScript trap: Numbers are doubles, so there is no wraparound to rely on. A free-running cursor incremented with plain + loses integer precision past 2**53 and your wrap logic quietly stops being a wrap; force uint32 semantics with (x + 1) >>> 0 and compute the length as (write - read) >>> 0 so it survives the rollover.
- ✓A TypedArray is real contiguous memory: one 64-byte cache line carries eight Float64 or sixteen Int32, and the prefetcher works.
What Circular Buffer actually is
Circular Buffer in JavaScript: what you actually reach for
JavaScript implementation
// Contiguous storage, power-of-two capacity, free-running uint32 cursors.
class RingBuffer {
#buf; #mask; #read = 0; #write = 0;
constructor(capacity) {
if (capacity < 1 || (capacity & (capacity - 1)) !== 0) {
throw new RangeError("capacity must be a power of two");
}
this.#buf = new Array(capacity).fill(null); // packed from birth; never `delete`
this.#mask = capacity - 1;
}
get size() {
return (this.#write - this.#read) >>> 0; // >>> 0 survives the uint32 rollover
}
push(v) { // overwrite-oldest
if (this.size === this.#buf.length) {
this.#read = (this.#read + 1) >>> 0;
}
this.#buf[this.#write & this.#mask] = v;
this.#write = (this.#write + 1) >>> 0; // plain ++ drifts past 2**53
}
shift() {
if (this.#read === this.#write) return undefined;
const i = this.#read & this.#mask;
const v = this.#buf[i];
this.#buf[i] = null; // release for GC, keep it packed
this.#read = (this.#read + 1) >>> 0;
return v;
}
}
// Cross-worker SPSC: cursors in an Int32Array over a SharedArrayBuffer,
// published with Atomics.store after the payload write, read with Atomics.load.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(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Circular Buffer?
Nothing in the language ships a ring buffer. The contiguous option is a TypedArray over an ArrayBuffer (Float64Array, Int32Array, Uint8Array), which stores raw values with no per-element object header. For arbitrary values you preallocate with new Array(n).fill(null) and do the index arithmetic yourself. The cross-thread single-producer-single-consumer version is SharedArrayBuffer plus Atomics.load, Atomics.store, Atomics.wait and Atomics.notify over an Int32Array or BigInt64Array; in the browser that requires cross-origin isolation via COOP and COEP headers, and in Node it means worker_threads. Atomics.wait throws on the browser main thread because that agent may not block.
What is the most common JavaScript mistake when implementing Circular Buffer?
Numbers are doubles, so there is no wraparound to rely on. A free-running cursor incremented with plain + loses integer precision past 2**53 and your wrap logic quietly stops being a wrap; force uint32 semantics with (x + 1) >>> 0 and compute the length as (write - read) >>> 0 so it survives the rollover. The nastier one is that TypedArrays swallow out-of-range writes: buf[buf.length] = v on a Float64Array is a silent no-op, while the same line on a plain Array grows it past its own capacity. An off-by-one therefore either vanishes or corrupts the invariant, and neither throws. Nothing preempts a synchronous method, so single-threaded rings need no locks at all.
How does Circular Buffer actually perform in JavaScript?
A TypedArray is real contiguous memory: one 64-byte cache line carries eight Float64 or sixteen Int32, and the prefetcher works. A plain Array is a vector of pointers, so you pay a dereference per element even though the indices are perfectly sequential. Keep it in packed elements kind by filling at construction and never leaving holes or mixing small integers, doubles and objects in the same array. shift on a large Array is an O(n) move. Each Atomics operation is a full barrier, so batch the cursor publication rather than storing per element. Time complexity is O(1) 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.