Using encode() to Convert Strings to Uint8Array
You'll learn how encode() transforms JavaScript strings into UTF-8 byte arrays for binary operations.
What encode() Does
When you call encode() on a TextEncoder instance, it takes a JavaScript string and converts it into a Uint8Array containing the UTF-8 byte representation of that string. This is essential when you need to work with binary data formats, send text over network protocols that expect bytes, or interface with APIs that require typed arrays.
The Transformation Process
const encoder = new TextEncoder();
// Simple ASCII string
const bytes = encoder.encode('Hello');
console.log(bytes); // Uint8Array(5) [72, 101, 108, 108, 111]
// Each byte represents one character's UTF-8 code
// 'H' → 72, 'e' → 101, 'l' → 108, 'l' → 108, 'o' → 111
Think of encode() like a translator that converts human-readable text into a language computers use for binary operations—individual bytes.
Working with Multi-byte Characters
UTF-8 uses multiple bytes for non-ASCII characters:
const encoder = new TextEncoder();
const emoji = encoder.encode('👋');
console.log(emoji); // Uint8Array(4) [240, 159, 145, 139]
// The wave emoji needs 4 bytes in UTF-8
const mixed = encoder.encode('Café');
console.log(mixed); // Uint8Array(5) [67, 97, 102, 195, 169]
// 'é' takes 2 bytes (195, 169)
The returned Uint8Array is ready for any binary operation—writing to files, sending over network sockets, or processing with DataView.
Key Takeaway: encode() converts JavaScript strings into Uint8Array objects containing UTF-8 encoded bytes, enabling you to bridge the gap between text and binary data formats.