How to Convert a JavaScript Byte Array to a String?

In JavaScript, you can convert an array of bytes to string by using the TextDecoder API with UTF-8 encoding, for example, in the following way:

function fromBinaryArray(bytes) {
  const decoder = new TextDecoder('utf-8');
  return decoder.decode(bytes);

console.log(fromBinaryArray(new Uint8Array([240, 159, 166, 138]))); // '🦊'
console.log(fromBinaryArray(new Uint8Array([227, 129, 147, 227, 130, 147, 227, 129, 171, 227, 129, 161, 227, 129, 175]))); // 'こんにちは'
console.log(fromBinaryArray(new Uint8Array([102, 111, 111, 98, 97, 114]))); // 'foobar'

In this example, the TextDecoder.decode() method takes an array of UTF-8 encoded bytes of a string as input and decodes it into the original string. You can use this conversion to help you with tasks such as decoding binary data, parsing network protocols, or reading data from files.

Please note that the values in the Uint8Array are UTF-8 encoded bytes, and not code points. UTF-8 encoding represents Unicode code points using one to four 8-bit bytes. For example, in the case of [240, 159, 166, 138], the byte sequence "[240, 159, 166, 138]" represents the Unicode code point U+1F98A, which is the fox face emoji (🦊).

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.