Using decode() to Convert Bytes to Strings
You'll learn how to transform raw binary data stored in a Uint8Array or ArrayBuffer back into readable JavaScript strings using TextDecoder's decode() method.
What decode() Does
Once you have a TextDecoder instance (which you learned to create in the previous lesson), you use its decode() method to convert binary byte data back into a human-readable string. This is the reverse operation of encode() — instead of turning text into bytes, you're turning bytes back into text.
The decode() method accepts either a Uint8Array or an ArrayBuffer and interprets those bytes according to the encoding you specified when creating the TextDecoder (typically UTF-8).
How It Works
Think of decode() as a translator that reads binary instructions and speaks them out loud as words. You hand it a Uint8Array containing bytes, and it returns the corresponding string:
const decoder = new TextDecoder(); // defaults to UTF-8
const bytes = new Uint8Array([72, 101, 108, 108, 111]); // "Hello" in UTF-8
const text = decoder.decode(bytes);
console.log(text); // "Hello"
You can also pass an ArrayBuffer directly:
const buffer = new ArrayBuffer(5);
const view = new Uint8Array(buffer);
view.set([72, 101, 108, 108, 111]);
const text = decoder.decode(buffer);
console.log(text); // "Hello"
The decoder handles all the complexity of interpreting multi-byte UTF-8 characters correctly, turning raw bytes back into the original string.
Key Takeaway: The decode() method converts binary data (Uint8Array or ArrayBuffer) back into JavaScript strings by interpreting the bytes according to the TextDecoder's encoding (typically UTF-8).