JavaScript Atomics compareExchange() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Atomics

Definition

Atomics.compareExchange(typedArray, index, expectedValue, replacementValue) looks at the element at index. If it is equal to expectedValue, it writes replacementValue; if not, it writes nothing. Either way it returns the element’s old value, and the check and the write happen as one atomic step. This is the famous “compare and swap” (CAS). Since the method never says “yes” or “no” directly, you test old === expectedValue to learn whether your write happened. With it you can build locks, one-time claims, and safe “read, compute, write” updates.

Remember
Atomics.compareExchange(a, i, expected, replacement)   -> old value

if a[i] === expected:  a[i] = replacement
else:                  nothing is written

success = (returned value === expected)
lock:  Atomics.compareExchange(lock, 0, 0, 1) === 0  -> I own it

Syntax

It takes four arguments: the array, the position, the value you expect, and the value to write.

JavaScript
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)
CallWhat it does
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)Writes replacementValue only when the element equals expectedValue, then returns the value it found.
Atomics.compareExchange(lock, 0, 0, 1)Lock pattern: change 0 (free) to 1 (taken). A return value of 0 means you got the lock; 1 means somebody else holds it.

Available since ES2017. It is the most powerful Atomics write: Atomics.exchange(), Atomics.add(), and friends could all be written as a compareExchange() retry loop.

Library declarations
JavaScript
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)
// returns the old element value, whether or not it wrote

// typedArray: integer typed arrays only (Int8 ... BigUint64)
// expectedValue and replacementValue: Number, or BigInt for BigInt arrays

Parameters

ParameterDescription
typedArrayRequired. An integer typed array (Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, BigUint64Array), shared or not.
indexRequired. The element to test and maybe replace. An invalid position throws a RangeError.
expectedValueRequired. The value the element must hold for the write to happen. It is first converted to the element type, so for a Uint8Array an expected 256 is treated as 0.
replacementValueRequired. The value to write when the comparison succeeds. Use BigInts for BigInt64Array and BigUint64Array.

Return Value

Return ValueDescription
Number or BigIntThe element value found before the operation. It equals expectedValue exactly when the replacement was written.

JavaScript Examples

Example 1 — Only One Worker Gets the Lock

Slot 0 is a lock: 0 means free and 1 means taken. Whoever turns 0 into 1 first owns it; everyone else is told to wait.

JavaScript
const lock = new Int32Array(1);   // 0 = free, 1 = taken

function tryLock(name) {
  const old = Atomics.compareExchange(lock, 0, 0, 1);
  return name + (old === 0 ? " got the lock" : " must wait");
}

console.log(tryLock("worker A"));   // worker A got the lock
console.log(tryLock("worker B"));   // worker B must wait
Atomics.store(lock, 0, 0);          // A releases the lock
console.log(tryLock("worker B"));   // worker B got the lock
Try It Yourself

How It Works

  1. Try to turn 0 into 1. Worker A finds 0, so the 1 is written and the old value 0 comes back: A owns the lock.
  2. The second try finds 1. Worker B expects 0 but the slot holds 1. Nothing is written, and the returned 1 tells B to wait.
  3. Release with a plain store. When A stores 0 again, B’s next attempt succeeds. Real code would sleep with Atomics.wait() instead of retrying blindly.

Example 2 — Compare the Result with the Expected Value

compareExchange() returns the old value in both cases. Comparing it with what you expected tells you whether you succeeded.

JavaScript
const value = new Int32Array(1);
Atomics.store(value, 0, 5);

const first = Atomics.compareExchange(value, 0, 5, 8);
console.log(first + " " + (first === 5) + " " + value[0]);    // 5 true 8

const second = Atomics.compareExchange(value, 0, 5, 9);
console.log(second + " " + (second === 5) + " " + value[0]);  // 8 false 8
Try It Yourself

How It Works

  1. The match succeeds. The slot holds 5 as expected, so 8 is written and the returned old value is 5.
  2. The second expectation is stale. It still expects 5, but the slot now holds 8. The call writes nothing and returns 8.
  3. Read the verdict. returned === expected is true for the first call and false for the second; the slot stays 8.

Example 3 — A Retry Loop That Keeps the Maximum

There is no Atomics.max(), but a compareExchange() loop can build one: read, decide, and write only if nobody changed the value meanwhile.

JavaScript
const best = new Int32Array(1);

function offer(score) {
  for (;;) {
    const current = Atomics.load(best, 0);
    if (score <= current) return false;
    if (Atomics.compareExchange(best, 0, current, score) === current) return true;
  }
}

console.log(offer(40));               // true
console.log(offer(25));               // false
console.log(offer(90));               // true
console.log(Atomics.load(best, 0));   // 90
Try It Yourself

How It Works

  1. Read, then decide. If the offered score is not higher than the current best, the function stops and returns false, as for 25.
  2. Write only if unchanged. compareExchange() writes the new score only when the slot still holds the value we read. If another thread got there first, the loop simply reads again.
  3. The best score wins. After offering 40, 25, and 90 the slot holds 90, and no higher score can ever be overwritten by a lower one.

Browser & Runtime Support

Atomics.compareExchange() has been available since ES2017 and works on shared and normal integer typed arrays in modern engines.

✓ Baseline · ES2017

Atomics.compareExchange()

Supported in all modern browsers and in Node.js, Deno, and Bun.

95% Modern browser support
Google Chrome Modern versions · Desktop & Mobile
Full support
Mozilla Firefox Modern versions · Desktop & Mobile
Full support
Apple Safari Modern versions · macOS & iOS
Full support
Microsoft Edge Modern versions · Chromium
Full support
Opera Modern versions
Full support
Samsung Internet Modern versions · Android
Full support
Internet Explorer No Atomics object
Not supported
Node.js Current releases · checked on Node 24
Supported
Deno Current releases
Supported
Bun Current releases
Supported
Atomics.compareExchange() Excellent

Bottom line: Ready for production use. Locks that are shared between browser workers need SharedArrayBuffer, which browsers enable only on cross-origin isolated pages.

Frequently Asked Questions

Always the old element value, whether it wrote or not. The write happened exactly when that returned value equals your expectedValue.
Use 0 for free and 1 for taken. Atomics.compareExchange(lock, 0, 0, 1) === 0 means you now own the lock. Release it with Atomics.store(lock, 0, 0), and wake waiters with Atomics.notify().
Because a successful claim returns 0, which is falsy. Compare the result with the expected value instead of using it directly as a condition.
You read the current value, compute a new one, and call compareExchange() with the value you read. If it returns something else, another thread changed it, so you read again and retry.
Yes, to the element type. With a Uint8Array an expected value of 256 becomes 0, so it matches a slot that holds 0. Keep values in range to avoid surprises.

Next: Atomics.exchange()

Swap a new value in and take the previous one out, with no condition.

exchange() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful