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

Circular Buffer Implementation in JavaScript

11 min readbeginner
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

  • ✓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

A ring buffer stores a fixed number of elements in one contiguous block and moves two integer indices instead of moving data: writes advance one cursor, reads advance the other, and both wrap at the end of the block. Nothing is ever shifted and no node is ever allocated, which is why it beats a linked structure at the same big-O. The one real design constraint is that head == tail is ambiguous: it means both empty and full. The three honest fixes are a separate count field, deliberately wasting one slot, or letting the cursors run free and masking with capacity minus one when capacity is a power of two. On top sit two policy choices: overwrite the oldest or reject the write when full, and whether one producer and one consumer may run without a lock, which needs only that the writer publishes its cursor after the payload and the reader loads that cursor before the payload. The eight languages diverge because each answers different questions: does an array hold values or references, does an integer wrap or trap or grow without bound, what does the memory model demand to publish a cursor, and must a vacated slot be cleared so the collector can reclaim what it held.

Circular Buffer in JavaScript: what you actually reach for

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.

JavaScript implementation

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. Assign null instead. They expect capacity fixed at construction and never grown, capacity a power of two with & mask, real privacy through #fields rather than an underscore convention, and size exposed as a getter computed from the two cursors rather than a mutable public field.
javascript
// 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 Free

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

Performance in JavaScript, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) 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 Circular Buffer between languages.

Real-World Applications

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

Interview Tips & Practice

Circular Buffer appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Circular Buffer 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 Circular Buffer 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 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).

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.