Course contentsShow
← JavaScript
Lesson 2347 of 2,72348. Working with Binary DataFree lesson

Creating a TextDecoder Instance

Instantiating TextDecoder with an encoding label (defaults to UTF-8) for decoding byte arrays.

Creating a TextDecoder Instance

You'll learn how to create a TextDecoder object that can convert byte arrays back into readable strings.

What Is a TextDecoder Instance?

A TextDecoder is an object that knows how to interpret byte arrays and turn them back into human-readable text. Think of it like a language interpreter who can read encoded messages and speak them back to you in your native language.

Just like TextEncoder needed to be instantiated before encoding, you need to create a TextDecoder instance before you can decode byte arrays.

The Basic Constructor

You create a decoder using the new keyword:

const decoder = new TextDecoder();

This creates a decoder that defaults to UTF-8 encoding—the same format that TextEncoder uses by default.

Specifying an Encoding Label

The TextDecoder constructor accepts an optional encoding label as its first argument. This tells the decoder what character encoding to expect in the byte data:

const utf8Decoder = new TextDecoder('utf-8');
const latin1Decoder = new TextDecoder('iso-8859-1');
const utf16Decoder = new TextDecoder('utf-16');

If you don't specify an encoding, UTF-8 is used automatically—which matches what most web APIs and TextEncoder produce.

Why This Matters

You need the correct decoder for the encoding that was used to create the bytes. If someone sends you bytes encoded in UTF-16, but you try to decode them with a UTF-8 decoder, you'll get gibberish. It's like trying to read Spanish with an English dictionary.

Key Takeaway: Create a TextDecoder instance with new TextDecoder() (defaults to UTF-8) or specify an encoding label like new TextDecoder('utf-16') to match the byte data's format.