How to Base64 Encode and Decode in JavaScript
John Mwaniki / Updated on 07 Jul 2024Base64 encoding is a binary-to-text encoding scheme that represents binary data in an ASCII string format by converting it into a string of upper and lower-case letters (A-Z, a-z), numbers (0-9), and symbols ("+", "/" and "="), where "=" is used as a padding suffix.
This encoding provides a convenient way to transmit binary data, such as images or files, over text-based protocols, like email or HTTP, where only ASCII characters are allowed.
By converting binary data into a text format, Base64 ensures that the data remains intact during transmission without the risk of being altered or corrupted. It is commonly used in web development, data serialization, and various applications where efficient and safe data transfer between systems is essential.
Base64 Encoding in JavaScript
JavaScript has a built-in function, btoa()
, which stands for "binary to ASCII" for encoding data into Base64 strings.
Example
var originalData = "I love programming!";
var encodedData = btoa(originalData);
console.log(encodedData);
Output:
SSBsb3ZlIHByb2dyYW1taW5nIQ==
Base64 Decoding in JavaScript
JavaScript offers the built-in atob()
function, which stands for "ASCII to binary" for decoding Base64 strings back into the original binary data.
Example
var encodedData = "SGVsbG8sIFdvcmxkIQ==";
var decodedData = atob(encodedData);
console.log(decodedData);
Output:
I love programming!