Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Atomics.xor() function in JavaScript
The Atomic object of JavaScript is an object that provides atomic operations such as add, sub, and, or, xor, load, store etc. as static methods. These methods are used with SharedArrayBuffer objects for thread-safe operations in multi-threaded environments.
The xor() function of the Atomics object accepts an array, position, and value, then performs a bitwise XOR operation on the value at the given position atomically.
Syntax
Atomics.xor(typedArray, index, value)
Parameters
- typedArray - A shared integer typed array (Int8Array, Uint8Array, Int16Array, etc.)
- index - The position in the array to operate on
- value - The number to XOR with
Return Value
Returns the old value at the specified position before the XOR operation was performed.
How XOR Operation Works
XOR (exclusive OR) returns 1 when bits are different and 0 when they are the same:
Example
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var arrayBuffer = new SharedArrayBuffer(16);
var data = new Uint8Array(arrayBuffer);
data[0] = 30;
// Perform XOR operation: 30 XOR 3 = 29
var oldValue = Atomics.xor(data, 0, 3);
var newValue = Atomics.load(data, 0);
document.write("Old value: " + oldValue + "<br>");
document.write("New value after XOR: " + newValue);
</script>
</body>
</html>
Output
Old value: 30 New value after XOR: 29
Multiple XOR Operations Example
<html>
<head>
<title>Multiple XOR Example</title>
</head>
<body>
<script type="text/javascript">
var buffer = new SharedArrayBuffer(8);
var array = new Uint8Array(buffer);
array[0] = 15; // Binary: 00001111
document.write("Initial value: " + array[0] + "<br>");
// XOR with 7 (Binary: 00000111)
Atomics.xor(array, 0, 7);
document.write("After XOR with 7: " + Atomics.load(array, 0) + "<br>");
// XOR again with 7 to restore original
Atomics.xor(array, 0, 7);
document.write("After XOR with 7 again: " + Atomics.load(array, 0));
</script>
</body>
</html>
Output
Initial value: 15 After XOR with 7: 8 After XOR with 7 again: 15
Key Points
- XOR operation is reversible - XORing twice with the same value returns the original
- Atomics.xor() is thread-safe for use with SharedArrayBuffer
- Works only with integer typed arrays, not regular arrays
- Returns the previous value before the operation
Conclusion
Atomics.xor() provides thread-safe bitwise XOR operations on shared memory. It's essential for multi-threaded JavaScript applications using Web Workers with SharedArrayBuffer.
