DEV Community

Mastering JS
Mastering JS

Posted on

2 2

3 Neat toString() Tricks in JavaScript

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!
Enter fullscreen mode Exit fullscreen mode

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...'
Enter fullscreen mode Exit fullscreen mode

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]'
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay