toString() MethodThe toString() method is a universal method in JavaScript that returns a string representing the specified object or primitive value.
Every object in JavaScript has a toString() method. While the default behavior can sometimes be unhelpful (e.g., returning "[object Object]"), many built-in objects override it to provide more useful, human-readable output.
toString() with PrimitivesYou can call toString() on any primitive value (except null and undefined) to get its string representation.
let myNum = 123; let myBool = true;console.log(myNum.toString()); // "123" console.log(myBool.toString()); // "true"
toString() with Numbers (Radix)The toString() method for numbers accepts an optional radix (or base) parameter. This allows you to convert a number into its binary, octal, or hexadecimal string representation.
The radix must be an integer between 2 and 36.
let num = 10;console.log(num.toString()); // Base 10 (default) -> "10" console.log(num.toString(2)); // Base 2 (binary) -> "1010" console.log(num.toString(8)); // Base 8 (octal) -> "12" console.log(num.toString(16)); // Base 16 (hexadecimal) -> "a"
toString() with ArraysWhen called on an array, toString() converts the array to a comma-separated string of its elements.
const fruits = ["Banana", "Orange", "Apple", "Mango"];console.log(fruits.toString()); // "Banana,Orange,Apple,Mango"
toString() with ObjectsBy default, calling toString() on a generic object returns the unhelpful string "[object Object]". To get meaningful output, you often need to override this method or use JSON.stringify().
const person = {name: "John", age: 30};
console.log(person.toString()); // "[object Object]"
// For useful output, use JSON.stringify()
console.log(JSON.stringify(person)); // '{"name":"John","age":30}'
How would you convert the number `15` into its hexadecimal string representation?