Base64 Encoding Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Base64 Encoding runs in O(n) time and O(n) space, in JavaScript as in every other language.
- ✓Two different worlds. In the browser: `btoa(binaryString)` and `atob(base64)`, both defined over 'binary strings' where each code unit is one byte, plus `TextEncoder`/`TextDecoder` to get real UTF-8 bytes.
- ✓A reviewer rejects `btoa(someUserString)` on sight: the only correct input to `btoa` is a string produced from bytes, so `TextEncoder` must appear somewhere.
- ✓The JavaScript trap: `btoa` is a latin-1 function wearing a string API. `btoa('Hello \u{1F44B}')` throws InvalidCharacterError, because the emoji's surrogate code units exceed 0xFF.
- ✓`btoa`/`atob` force a full intermediate JS string; engines can hold it as one-byte latin-1, but you still pay two conversions plus a fresh result string for `btoa` -- the result is ASCII so V8 keeps it one byte per char; the cost is the extra copy, not the width.
What Base64 Encoding actually is
Base64 Encoding in JavaScript: what you actually reach for
JavaScript implementation
// Browser: bytes <-> base64 without the latin-1 trap
function bytesToBase64(bytes) {
let bin = "";
const CHUNK = 0x8000; // spread/apply blows the stack past ~100k args
for (let i = 0; i < bytes.length; i += CHUNK) {
bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));
}
return btoa(bin);
}
function base64ToBytes(b64) {
const bin = atob(b64);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
const b64 = bytesToBase64(new TextEncoder().encode("Hello, \u{1F44B}"));
console.log(b64, new TextDecoder().decode(base64ToBytes(b64)));
// btoa("Hello, \u{1F44B}") would throw InvalidCharacterError: code unit > 0xFF
// Node instead: Buffer.from(s, "utf8").toString("base64url")
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Base64 Encoding?
Two different worlds. In the browser: `btoa(binaryString)` and `atob(base64)`, both defined over 'binary strings' where each code unit is one byte, plus `TextEncoder`/`TextDecoder` to get real UTF-8 bytes. Newer engines also expose `Uint8Array.prototype.toBase64()` and `Uint8Array.fromBase64()`, which skip the string detour entirely -- feature-detect before relying on them. In Node: `Buffer.from(str, 'utf8').toString('base64')` and `Buffer.from(b64, 'base64')`, with 'base64url' as a first-class encoding name.
What is the most common JavaScript mistake when implementing Base64 Encoding?
`btoa` is a latin-1 function wearing a string API. `btoa('Hello \u{1F44B}')` throws InvalidCharacterError, because the emoji's surrogate code units exceed 0xFF. Worse is the case that does NOT throw: `btoa('café')` succeeds and encodes 0xE9 -- one latin-1 byte -- where every other language in this list would have produced the two UTF-8 bytes 0xC3 0xA9. The round trip through `atob` looks perfect locally, and only the Python or Go service on the other end sees mojibake. Always encode through `TextEncoder` first.
How does Base64 Encoding actually perform in JavaScript?
`btoa`/`atob` force a full intermediate JS string; engines can hold it as one-byte latin-1, but you still pay two conversions plus a fresh result string for `btoa` -- the result is ASCII so V8 keeps it one byte per char; the cost is the extra copy, not the width. `String.fromCharCode.apply(null, hugeArray)` throws RangeError once the argument count passes roughly 100k, so 32 KB chunks are the standard shape. Node's Buffer base64 path is native C++ with SIMD and is an order of magnitude faster than any JS loop; the newer `Uint8Array.toBase64` gives browsers the same shortcut when available. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.