If you're new to JavaScript, you may have encountered .toString() when working with integers, strings, or arrays. But what precisely does this technique perform, and how can you apply it successfully in your code?
In this article, we'll look at the JavaScript .toString() function, explain its purpose, and present real-world examples and scenarios to demonstrate its usefulness, particularly for converting integers to other bases such as binary or hexadecimal.
What is .toString() in JavaScript?
.toString() is a built-in JavaScript method used to convert values (like numbers, booleans, and objects) into their string representations. It can also be used to convert numbers to different numeral systems such as binary (base 2), octal (base 8), or hexadecimal (base 16).
Syntax
value.toString([radix])
value: Any number, boolean, or object (exceptnullorundefined)radix(optional): An integer between 2 and 36 that represents the base in mathematical numeral systems
Why Use .toString()?
To convert numbers or booleans to strings
To display formatted text
To convert a number to binary, hexadecimal, or other base formats
To debug or log object values as strings
Scenarios Where .toString() Is Useful
1. Convert a number to a string
const price = 100;
console.log(price.toString()); // "100"
Useful when you want to display numbers as part of a message or UI element.
2. Convert boolean to string
const isLoggedIn = true;
console.log(isLoggedIn.toString()); // "true"
Helps when storing or transmitting data in string format.
3. Convert a number to binary (base 2)
const number = 10;
console.log(number.toString(2)); // "1010"
Ideal for bitwise operations, binary logic, or learning how numbers work under the hood.
4. Convert to hexadecimal (base 16)
const colorCode = 255;
console.log(colorCode.toString(16)); // "ff"
Useful in web development for converting colors or memory addresses.
Examples and Output
const num = 123;
console.log(num.toString()); // "123" (default: base 10)
console.log(num.toString(2)); // "1111011" (binary)
console.log(num.toString(8)); // "173" (octal)
console.log(num.toString(16)); // "7b" (hexadecimal)
console.log((true).toString()); // "true"
Simple Exercise: Convert 255 to Binary, Octal, and Hexadecimal
const value = 255;
console.log("Binary:", value.toString(2)); // Output: "11111111"
console.log("Octal:", value.toString(8)); // Output: "377"
console.log("Hexadecimal:", value.toString(16)); // Output: "ff"
This shows how .toString(radix) allows you to change number formats easily, all with one method.
Final Thoughts
The JavaScript .toString() technique is extremely useful and needed for any developer. Whether you're formatting output, converting data kinds, or working with numerical systems, this technique should be in your toolkit.