Most JavaScript objects and primitive values have a toString()
function that converts the value to a string. Different values have different toString()
methods, and some toString()
methods have cool surprises. Here's 3:
1) Numbers have a toString()
function that supports different bases
Converting decimal to binary in JavaScript is easy, because JavaScript numbers have a toString()
function that takes a radix
parameter that specifies which base to use.
let x = 42;
x.toString(2); // '101010'
x.toString(16); // '2a', hexadecimal!
2) Encode data as base64 using Node.js Buffers
Node buffers have a toString()
function that takes an encoding parameter. Calling toString('base64')
converts the buffer into a base64 string, which is handy if you need to convert a file into base64 for email attachments.
const fs = require('fs');
const buf = fs.readFileSync('./package.json');
buf.toString('base64'); // 'ewogICJuYW1lIjog...'
3) Custom Tags for Objects
Objects' toString()
is not very useful by default: the output is just [object Object]
. However, you can make this output slightly more useful by setting the object's Symbol.toStringTag
:
const obj = {};
obj[Symbol.toStringTag] = 'Test';
obj.toString(); // '[object Test]'
Top comments (0)