JavaScript Data Structures - Typed Arrays I
Written by Ian Elliot   
Thursday, 28 February 2019
Article Index
JavaScript Data Structures - Typed Arrays I
Block Copy


Block Copy

One of the very standard operations that you have to perform with binary data is moving it from one place to another. The direct and not very efficient way of doing this is to simply write a suitable for loop that transfers the data one element at a time. 

A better method is to use the typed array's set method which will transfer the contents of one array or part of an array to another. 


copys all of the contents of array2 into array1 and


copys all of array2 into array1 starting at array1[offset]

If for any reason the copy operation results in an attempt to access beyond the end of array1 then an exception is thrown. 

You can even use set to move data within a single ArrayBuffer. For example, if we set the first 50 bytes of an array to 255 and then define a view of these first 50 bytes we can use this to move all 50 to the top of the array:

var bytes=new Uint8Array(100);
for(var i=0;i<50;i++){
var buffer= bytes.buffer;
var start=new Uint8Array(buffer,0,50); bytes.set(start,50);

In fact we can make this example even simpler by using the subarray method which constructs a new view on the same buffer that is:

var array2=array1.subarray(start,length);

returns a view, array2, into the same ArrayBuffer as array1 uses. The new view starts with array1[start] and has length elements.

So to get we could write the previous example as:

var start=bytes.subarray(0,50); bytes.set(start,50);

or if you prefer one-liners:



This might be all you need to know about typed arrays but there is more. Specifically there is the difficult question of byte order that we need to solve and how to work with binary data that isn't all of one type, i.e. a binary structure or record. You can find out how all of this works in part II of our look at typed arrays. 

JavaScript Data Structures 



  1. The Associative Array
  2. The String Object
  3. The Array object
  4. Speed dating - the art of the JavaScript Date object
  5. Doing JavaScript Date Calculations
  6. A Time Interval Object
  7. Collection Object
  8. Stacks, Queue & Deque
  9. The Linked List
  10. A Lisp-like list
  11. The Binary Tree
  12. Bit manipulation
  13. Typed Arrays I
  14. Typed Arrays II
  15. Master JavaScript Regular Expressions
    * First Draft

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.


raspberry pi books



or email your comment to:





Last Updated ( Thursday, 28 February 2019 )