Shared binary views versus copies
Quick answer
Multiple views can refer to one buffer. A change through one view can be visible through another; copying creates separate storage.
How it works
new Uint8Array(buffer, byteOffset, length) selects bytes in the buffer. For wider elements, byteOffset must be aligned to element size. subarray(begin,end) creates a view of the same memory; slice(begin,end) copies elements. set(source,offset) copies elements into an existing view; it does not grow the target. Distinguish byte offsets from element indices.
Local examples
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const a=new Uint8Array([1,2,3]);const v=a.subarray(1);v[0]=8;console.log(JSON.stringify([...a]),v.byteOffset);})()Expected console output:
[1,8,3] 1The subarray shares bytes.
Run in a fresh browser document. Uses synthetic local data; actual ByteMind editor support is unverified.
(async () => {const a=new Uint8Array([1,2,3]);const v=a.slice(1);v[0]=8;console.log(JSON.stringify([...a]),v.buffer===a.buffer);})()Expected console output:
[1,2,3] falseThe default slice allocates separate storage.
Common mistakes
Do not assume a subarray isolates mutations. Copy a selected view before handing it to code that may change it.
Practice
Compare mutations to subarray and slice of the same four-element byte array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Shared binary views versus copies — Knowledge Check
Apply the concept and reason about local example output.
Which method normally creates a shared typed-array view?
What does typedArray.set(source, offset) use for offset?
What must a Uint16Array byteOffset be aligned to?
What is the expected console output of Shared binary views versus copies example 1?
(async () => {const a=new Uint8Array([1,2,3]);const v=a.subarray(1);v[0]=8;console.log(JSON.stringify([...a]),v.byteOffset);})()What is the expected console output of Shared binary views versus copies example 2?
(async () => {const a=new Uint8Array([1,2,3]);const v=a.slice(1);v[0]=8;console.log(JSON.stringify([...a]),v.buffer===a.buffer);})()