Working With Uint8Array
In this lesson, you read and write single bytes in a Uint8Array, then take part of it with and without
a copy. In the last lesson, a TextEncoder encoded Zoë as four bytes: 90, 111, and then 195 and 171 for
the ë. The helper now holds them in a Uint8Array, and two of its habits would surprise the team lead’s
code.
The team lead’s Python keeps those bytes in a bytearray, so it can change them. It reads one byte by
index, 195, the first of the ë’s two bytes. Then, to watch one byte change, it writes 122, a
lowercase z, over the first byte. Real lowercasing happens on the string, before encoding:
data = bytearray([90, 111, 195, 171])
print(data[2])
data[0] = 122
print(list(data))
This prints 195 and [122, 111, 195, 171]. In JavaScript, the four bytes go into a Uint8Array with
new and an array literal. Indexing works as on an array: square brackets, counting from zero, as in
Python. Unlike Python, though, a negative index doesn’t count from the end. Writing works the same way:
assign to an index, and the byte changes in place:
const data = new Uint8Array([90, 111, 195, 171]);
console.log(data[2]);
data[0] = 122;
console.log(data);
The log shows 195, then the lowercase z’s 122 at the front, and the (4) says the length is still
four: