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

Understanding UTF-8 Byte Representation

How ASCII characters use one byte while other Unicode characters require multiple bytes in UTF-8.

Understanding UTF-8 Byte Representation

What you'll learn: How ASCII characters use one byte while other Unicode characters require multiple bytes in UTF-8.

The Core Idea

When you use TextEncoder to convert strings to Uint8Array, you're creating UTF-8 encoded data. UTF-8 is a variable-length encoding system: simple ASCII characters (like English letters, numbers, and common symbols) occupy just one byte, while characters from other scripts or special symbols require two, three, or even four bytes.

Think of it like packing luggage: a t-shirt (ASCII) fits in a small bag, but a winter coat (complex Unicode character) needs more space.

ASCII: The One-Byte Zone

Characters in the ASCII range (0-127) — like 'A', '5', or '!' — each encode to exactly one byte:

const encoder = new TextEncoder();
console.log(encoder.encode('Hello'));  
// Uint8Array(5) [72, 101, 108, 108, 111]
// 'H' = 72, 'e' = 101, etc. — 5 characters = 5 bytes

Beyond ASCII: Multi-Byte Characters

Non-ASCII characters require multiple bytes. For example, the Euro symbol '€' needs three bytes, and emojis typically need four:

console.log(encoder.encode('€'));  
// Uint8Array(3) [226, 130, 172] — 1 character = 3 bytes

console.log(encoder.encode('Hello €'));  
// Uint8Array(8) — 5 ASCII bytes + 3 bytes for €

This is why string.length (character count) and encoded.length (byte count) often differ. A string's byte size depends on which characters it contains, not just how many.

Key Takeaway: In UTF-8, ASCII characters (0-127) use one byte each, but most other Unicode characters require 2-4 bytes. Always check the encoded Uint8Array length to know the true byte size of your data.