iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
In JavaScript, convert text to binary bytes with TextEncoder, then turn those bytes back into text with TextDecoder. The encoding matters: the examples below use UTF-8, the practical default for exchanging new text data.
Convert text to UTF-8 bytes
A JavaScript string is text, not a byte array. Encoding the string produces bytes, represented here by a Uint8Array. The WHATWG Encoding Standard defines the API, and MDN documents that TextEncoder.encode() returns UTF-8 bytes.
const text = "Hello, 🌍";
const bytes = new TextEncoder().encode(text);
console.log(bytes); // Uint8Array containing the UTF-8 bytes
Because UTF-8 uses a variable number of bytes per character, the number of bytes is not necessarily the same as the number of characters in the string. The returned typed array is convenient for byte-oriented APIs. If an API specifically requires an ArrayBuffer, use bytes.buffer.
MDN: TextEncoder — encode() · WHATWG Encoding Standard
#1 Best Overall
Convert UTF-8 bytes back to text
Pass the byte array to TextDecoder.decode(). Its default encoding is UTF-8, matching the bytes produced by TextEncoder.
const decoded = new TextDecoder().decode(bytes);
console.log(decoded); // "Hello, 🌍"
For a complete round trip:
const text = "Hello, 🌍";
const bytes = new TextEncoder().encode(text);
const restored = new TextDecoder().decode(bytes);
console.log(restored === text); // true
Use the encoding that matches the original bytes when decoding. Choosing the wrong encoding can produce incorrect text or a decoding error. See MDN: TextDecoder.
Rank #2
Choose the right representation
“Binary” can mean the raw bytes an API processes, or a text representation of those bytes. For text conversion, TextEncoder and TextDecoder handle the text-to-byte and byte-to-text steps. Base64 is different: it represents bytes as ASCII text, often for transport or embedding. It is not encryption.
| What you need | Use | Result |
|---|---|---|
| UTF-8 bytes for an API or byte-processing task | TextEncoder |
A Uint8Array |
| Text reconstructed from bytes | TextDecoder with the matching encoding |
A JavaScript string |
| ASCII text representing bytes | Base64 conversion after encoding the text to bytes | A Base64 string, not raw bytes |
Encode Unicode text as Base64
The browser’s btoa() function expects a binary string whose characters represent individual byte values; it does not accept arbitrary Unicode text directly. Passing text such as "A café 🦄" straight to btoa() can throw. First encode the text as UTF-8, then map the byte values into a binary string for Base64 conversion. The reverse path uses atob() to obtain byte values, which are then decoded as UTF-8.
function bytesToBase64(bytes) {
const binaryString = Array.from(
bytes,
byte => String.fromCodePoint(byte)
).join("");
return btoa(binaryString);
}
function base64ToBytes(base64) {
const binaryString = atob(base64);
return Uint8Array.from(
binaryString,
char => char.codePointAt(0)
);
}
const text = "A café 🦄";
const bytes = new TextEncoder().encode(text);
const base64 = bytesToBase64(bytes);
const restored = new TextDecoder().decode(base64ToBytes(base64));
console.log(base64);
console.log(restored); // "A café 🦄"
These helpers follow the byte-array conversion pattern documented by MDN. Newer JavaScript runtimes may provide Base64 methods on typed arrays, but check compatibility in your target runtime before relying on them. For details on btoa(), including its input restrictions, see MDN: Window — btoa() and MDN: Window — atob().
Handle malformed byte sequences
By default, decoding malformed input uses replacement behavior, so invalid byte sequences can yield the replacement character rather than an exception. If your application needs invalid UTF-8 to fail explicitly, enable fatal decoding:
Rank #4
const decoder = new TextDecoder("utf-8", { fatal: true });
try {
const text = decoder.decode(bytes);
console.log(text);
} catch (error) {
console.error("The bytes could not be decoded as valid UTF-8", error);
}
A failure can mean the data is malformed or that UTF-8 is not the encoding used to create the bytes. The WHATWG Encoding Standard defines both replacement and fatal decoding behavior: Encoding Standard.
Check support in your JavaScript runtime
MDN marks TextEncoder.encode() and TextDecoder as widely available in browsers since January 2020. The Encoding API is defined by WHATWG; that browser compatibility statement should not be assumed to cover every embedded JavaScript runtime. Check the documentation for your target environment if you are not running in a browser.
Best Value
TextEncoder compatibility · TextDecoder compatibility
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

