JavaScript ArrayBuffer.prototype.detached
In JavaScript, the ArrayBuffer.prototype.detached
property indicates whether an ArrayBuffer instance has been transferred (detached) from its current context. This is especially important for web workers when dealing with large binary data for communication.
Syntax
const isDetached = arrayBufferInstance.detached;
const buffer = new ArrayBuffer(16); // Create an ArrayBuffer
const isDetached = buffer.detached; // Check if buffer is detached
console.log(isDetached); // Output: false
- arrayBufferInstance: It is an existing ArrayBuffer object.
- isDetached: It is a boolean value that represents the detached state.
Return Value
It will return true if detached otherwise false.
Example 1: The below example checks the detached state with property check.
function transferBufferToWorker(buffer) {
// Simulate transferring the buffer to a worker
return buffer;
// This does not transfer the buffer in reality
}
const originalBuffer =
new ArrayBuffer(10);
const transferredBuffer =
transferBufferToWorker(originalBuffer);
// Property check to determine
// if the buffer has been detached
if (transferredBuffer.byteLength === 0) {
console.log("The buffer has been transferred and is detached.");
} else {
console.log("The buffer remains in the current context.");
}
Output
The buffer remains in the current context.
Example 2: The below example ensure a detached state by the use of a utility function.
function transferBufferToWorker(buffer) {
// Simulate transferring the buffer to a worker
return buffer;
// This does not transfer the buffer in reality
}
// Utility function to check if the buffer is detached
function isBufferDetached(buffer) {
try {
// Attempt to create a new view on the buffer
new Uint8Array(buffer);
// Buffer is not detached
return false;
} catch (error) {
// Buffer is detached
return true;
}
}
const originalBuffer = new ArrayBuffer(10);
const transferredBuffer = transferBufferToWorker(originalBuffer);
// Check if the buffer is detached
// using the utility function
if (isBufferDetached(transferredBuffer)) {
console.log("The buffer has been transferred and is detached.");
} else {
console.log("The buffer remains in the current context.");
}
Output
The buffer remains in the current context.
Browser Support
- Chrome 114
- Edge 114
- Firefox 122
- Opera 100
- Safari 17.4
Contact Us