btoa() and atob() in the Browser
You'll learn how to encode and decode Base64 strings using the browser's built-in functions, plus their critical Unicode limitation.
What btoa() and atob() Do
The browser provides two global functions for Base64 operations:
btoa()("binary to ASCII") encodes a string into Base64atob()("ASCII to binary") decodes a Base64 string back to normal text
Think of them as translators: btoa() translates your text into the Base64 alphabet you learned earlier, and atob() translates it back.
Basic Usage
// Encoding with btoa()
const original = "Hello, World!";
const encoded = btoa(original);
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
// Decoding with atob()
const decoded = atob(encoded);
console.log(decoded); // "Hello, World!"
The Unicode Trap
Here's the critical limitation: btoa() only works with single-byte characters. If you try encoding Unicode characters (like emojis or non-Latin text), it throws an error:
btoa("Hello 👋"); // ❌ Error: Invalid character
This happens because btoa() expects each character's code to fit in one byte (0-255), but Unicode characters can be much larger.
The workaround: Use TextEncoder and TextDecoder (which you've already learned) to convert Unicode strings to bytes first, then manually convert those bytes to Base64 using the alphabet.
When to Use Them
Use btoa() and atob() for simple ASCII-only data like basic tokens or identifiers. For anything involving Unicode, you'll need a more robust approach combining typed arrays and manual Base64 encoding.
Key Takeaway: btoa() encodes ASCII strings to Base64 and atob() decodes them, but both fail with Unicode characters—you must handle Unicode separately using TextEncoder/TextDecoder.