Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Typed array length and indexing

`length` counts elements in a typed array view, not bytes. Bracket indexing starts at zero, and writing past the end does not extend the view.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

view.length
view[index]
view[index] = value
view.at(index)
new Uint16Array(buffer, byteOffset)
new Uint16Array(buffer, byteOffset, length)

TypedArray.length/indexing covers the element count and element access of a typed array view, such as a Uint16Array. view.length is an inherited getter with no setter. It counts elements; view.byteLength counts bytes in the view, and view.buffer.byteLength counts bytes in the whole buffer. Assigning to view.length does not resize the view and throws TypeError in strict mode.

Element indices are integers from 0 through view.length - 1. view[0] and view["0"] refer to the same element. Keys such as "01" and "1.0" are ordinary property names, not element indices. Numeric view[-0] behaves like view[0], but view["-0"] returns undefined.

Reading an invalid element index returns undefined. Writing to one leaves the buffer unchanged and adds no element, even in strict mode, if value conversion succeeds. Conversion can still throw, for example when writing a Number to a BigInt64Array. At a valid index, the value is stored according to the element type. view[-1] does not count from the end; view.at(-1) does and returns the last element of a nonempty view.

When the constructor receives a resizable ArrayBuffer or a growable SharedArrayBuffer, omitting the third argument length (or passing undefined) creates a length-tracking view that counts whole elements from byteOffset to the current end of the buffer. With a fixed-length buffer, the same call creates a fixed-length view. In that case, the number of bytes from byteOffset to the end of the buffer must be a multiple of the element size in bytes, or the constructor throws RangeError. An explicit length fixes the element count while the view fits. If shrinking puts the view out of bounds, length reads as 0; regrowing the buffer can bring the view back in bounds. Buffer detachment also makes length read as 0. In either case, indexed reads return undefined, but at() throws TypeError.

Examples

"use strict";
{
  const view = new Uint16Array([10, 20]);
  view[1] = 65537;
  view[view.length] = 99;

  console.log(`${view.length} ${view.byteLength}`);
  console.log(`${view[0]} ${view[1]}`);
  console.log(`${view[view.length]} ${view[-1]} ${view.at(-1)}`);
}

Result

2 4
10 1
undefined undefined 1

Two `Uint16Array` elements occupy four bytes. Storing `65537` gives `1` because only the low 16 bits are kept. Writing at index `2` does not extend the view; `at(-1)` reads the last element.

Related lessons

  • JavaScript · Lesson 33 · Advanced · Version: 4
  • JavaScript · Lesson 34 · Advanced · Version: 4

Sources