Techsin
Techsin

Reputation: 532

Understanding the concept of typed arrays in JavaScript

I want to know what are typed arrays in JavaScript (e.g. Int16Array, Uint32Array, Uint8ClampedArray, etc.). I am new to this byte level concept, as in I don't really get what is being said. For example if you take a look at this article when it talks about 32 bit manipulation I am lost then...
https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipulation-with-typed-arrays/

I know a character is two bytes in JavaScript and I know typed arrays are just a buffer(?) that stores byte then data view such as these three above are used to read/modify byte information in a certain way depending on their type. However, I am unable to understand how to use them or what benefit they have over "normal" arrays. Could someone explain the use cases and benefits of typed arrays?

Upvotes: 4

Views: 1908

Answers (1)

jfriend00
jfriend00

Reputation: 707298

Typed arrays are generally used when interfacing with the outside world where data comes in a specific non-javascript form and you want to access that data via javascript. Type arrays are used to create a specific view of a data buffer. The buffer is the raw data and the view is a method of reading/interpreting/accessing that data.

If you aren't interfacing with the outside world and aren't trying to deal with data created outside of javascript or sent to an agent outside of javascript, then one would typically just use a normal javascript array and not use buffers and typed arrays.

This is what the types you asked about are:

Int16Array: An array of 16-bit integers (signed) - 2 bytes per entry
Uint8Array: An array of 8-bit unsigned integers - 1 byte per entry
Uint32Array: An array of 32-bit unsigned integers - 4 bytes per entry

You can see a list of all the typed arrays here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays

When a variable is typed, that means that the variable has a very specific type and only that type. A type might be a string, a 16-bit signed integer, a floating point number, etc... In javascript, a variable can hold any kind of data, thus it isn't specifically typed. In other languages such as C, variables are generally predeclared to hold a specific type and (without using specific overrides) you can't assign data of different types to that variable.

Without intending to start an argument over the desirability of various language features, it is generally considered safer to program in typed languages and data can perhaps be manipulated faster by the execution engine, but untyped or weakly typed languages can sometimes be more flexible - making it simpler or cleaner to do some things.

Upvotes: 3

Related Questions