JS toString() Method

JavaScript toString() Method

The 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.


1. Using toString() with Primitives

You can call toString() on any primitive value (except null and undefined) to get its string representation.

toString() with Primitives

let myNum = 123;
let myBool = true;

console.log(myNum.toString()); // "123" console.log(myBool.toString()); // "true"


2. 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.

Number toString() with Radix

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"


3. toString() with Arrays

When called on an array, toString() converts the array to a comma-separated string of its elements.

Array toString() Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];

console.log(fruits.toString()); // "Banana,Orange,Apple,Mango"


4. toString() with Objects

By 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().

Object toString() Example

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}'


Exercise

?

How would you convert the number `15` into its hexadecimal string representation?