JavaScript toString(): How to Use It Effectively

Whether you’re a beginner or an experienced developer, understanding how JavaScript toString() works and its various applications will empower you to manipulate and display data effectively.

In this blog post, we’ll delve into:

  • The toString() method with an example
  • The toString() method result without a comma
  • How toString() method work on numbers
  • ToString() method on an object, null and undefined values
  • Covering everything from basic usage to advanced techniques.

Let’s get started!

JavaScript toString() function

The toString() function allows you to convert a value to its JavaScript string representation. It is available for most data types, including numbers, strings, objects, and even null and undefined.

Here’s the toString() JavaScript method syntax:

value.toString();

Let’s consider a simple example:

const message = "Hello, world!";
const msg = message.toString();

console.log(msg); 
// Output: "Hello, world!"

In this example, we apply the toString() function on the string variable message. Since the variable is already a JavaScript string, calling toString() doesn’t change the value.

JavaScript toString() parameters

The toString() function accepts an optional parameter called radix that can be used with the Number object to specify the base for representing a number as a string.

Here’s an explanation of the radix (optional) parameter:

  • This parameter specifies the base (between 2 and 36) for representing a number as a string. It is only applicable when calling toString() on a Number object.
  • If not provided, or if the radix is 10, the number is converted to a decimal (base 10) string.
  • If you specify a different radix, the number will be converted to a string using the specified base.
// Using toString() with numbers and the radix parameter
const decimalNumber = 40;
console.log(decimalNumber.toString());       
// Output: "40" (default radix is 10)

console.log(decimalNumber.toString(2));      
// Output: "101000" (binary representation)

console.log(decimalNumber.toString(8));      
// Output: "50" (octal representation)

console.log(decimalNumber.toString(16));  
// Output: "28" (hexadecimal representation)
JavaScript toString() Function
JavaScript toString() Function

Formatting numbers without comma using toString() JavaScript

By default, the toString() method adds commas to separate thousands of numbers. However, there may be cases where you want to remove these commas. To achieve this, we can use a combination of toString() and replace() methods.

Consider the following example:

const number = 1000000;
const stringWithoutCommas = number.toString().replace(/,/g, '');

console.log(stringWithoutCommas); 
// Output: "1000000"

Here, we convert the number 1000000 to a string using toString(). Then, we use the replace() method with a regular expression (/,/g) to remove the commas from the string.

JavaScript toString() on objects

The toString() method is also available for JavaScript objects. However, its default behavior is not always ideal. By default, calling toString() on an object returns a string that represents its type and memory address. Let’s consider an example:

const person = { name: "John", age: 30 };
const objString = person.toString();

console.log(objString); // Output: "[object Object]"

In the above example, calling toString() on the person object returns the string "[object Object]". This output is not very informative or useful. To customize the toString() output for objects, we can override the toString() method within the object’s prototype.

JavaScript number toString() method

The Number.toString() method is a specialized version of toString() that works specifically with numbers. It allows us to convert numbers to different number systems, such as binary, octal, and hexadecimal.

Let’s see a few examples of the JavaScript number toString() method:

const number = 42;

console.log(number.toString(2)); // Output: "101010"
console.log(number.toString(8)); // Output: "52"
console.log(number.toString(16)); // Output: "2a"

In this example, we use the toString() method with different radix values (2, 8, and 16) to convert the decimal number 42 to binary, octal, and hexadecimal, respectively.

JavaScript toString() for null

Calling toString() on null values throws “Cannot read properties of null (reading ‘toString’)”. Let’s illustrate this with an example:

const value = null;

// Cannot read properties of null (reading 'toString')
const nullString = value.toString(); 
console.log(nullString); 

How to resolve "cannot read properties of undefined (reading 'tostring')"?

It is always safe to check whether the value is null or empty before calling any method.

const value = null;
const nullString = (value && value.toString());
console.log(nullString); 
// Output: null

This code defines a variable value with a null value. Due to the short-circuiting behavior of the logical AND (&&) operator, the assignment of value.toString() is skipped, and nullString remains null. The final console.log() statement prints null to the console.

The toString() JavaScript options and formatting

The toString() method in the JavaScript method offers additional options and formatting possibilities. One such option is the radix parameter, which specifies the base for the number of conversions. By default, it is set to 10, but we can change it to any value between 2 and 36.

Here’s an example:

const number = 42;

console.log(number.toString(2)); // Output: "101010"
console.log(number.toString(8)); // Output: "52"
console.log(number.toString(16)); // Output: "2a"
In this example, we convert the number 42 to binary, octal, and hexadecimal using the toString() method with different radix values.

The toString() in JavaScript method on undefined

If you directly call the toString() method on an undefined value, you will get an error. This is because undefined is not an object, and attempting to access a property or method on undefined directly will result in a "Cannot read property 'toString' of undefined" error.

let undefinedValue;
console.log(undefinedValue.toString()); 
//Error: Cannot read properties of null (reading 'toString') 
To safely handle cases where the value could be undefined, you would typically want to check whether the value is defined before attempting to call methods on it.
function greet(t) {
  if (t === undefined) {
    return 'Value is undefined!';
  }
  return t;
}

let value; 
console.log(greet(value));
// Output: "Value is undefined!"
In the above example, the undefinedValue is implicitly converted to the string "undefined" when concatenated with the other string.

Conclusion

In this comprehensive guide, we have covered the ins and outs of JavaScript’s toString() method. We explored its usage on various data types, including strings, numbers, objects, null, and undefined.

Understanding how to customize the toString() output and leverage the additional options provided will enable you to manipulate and display data more effectively in your JavaScript applications.

Now that you’ve mastered the toString() method, it’s time to put your newfound knowledge into practice and create powerful JavaScript code.

Scroll to Top