Creating a TextEncoder Instance
You'll learn: How to create a TextEncoder object in JavaScript, which always encodes strings into UTF-8 byte sequences.
The Basics
Creating a TextEncoder instance is refreshingly simple—just call its constructor with no arguments:
const encoder = new TextEncoder();
That's it! Unlike many encoding tools in other languages where you specify which character encoding to use, JavaScript's TextEncoder always uses UTF-8 encoding. There are no configuration options or parameters to pass.
Why UTF-8 Only?
Think of TextEncoder as a specialized tool rather than a Swiss Army knife. The web standardized on UTF-8 as the universal encoding format because it handles all Unicode characters efficiently while remaining backward-compatible with ASCII. Since JavaScript strings are already Unicode-based, converting them to UTF-8 bytes is the most common and practical need.
If you try passing arguments to the constructor, they're simply ignored:
const encoder = new TextEncoder('ascii'); // Still UTF-8!
const another = new TextEncoder('utf-16'); // Still UTF-8!
Both instances above will encode text as UTF-8, regardless of what you attempted to specify.
Typical Usage Pattern
You typically create one encoder instance and reuse it throughout your code:
const encoder = new TextEncoder();
// Use it multiple times
const bytes1 = encoder.encode('Hello');
const bytes2 = encoder.encode('World');
Creating multiple instances is harmless but unnecessary since they all behave identically.
Key Takeaway: Instantiate TextEncoder with new TextEncoder()—no arguments needed, always UTF-8 encoding, ready to convert strings to byte arrays.