totn JavaScript

JavaScript: String toString() method

This JavaScript tutorial explains how to use the string method called toString() with syntax and examples.

Description

In JavaScript, toString() is a string method that is used to return a string representation or primitive value of an object. Because the toString() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the toString() method is:

string.toString();

Parameters or Arguments

There are no parameters or arguments for the toString() method.

Returns

The toString() method returns a string representing the calling object which is the primitive value of the object.

Note

  • The toString() method does not change the value of the original string.
  • You can also use the valueOf() method to return the primitive value of a String object.

Example

Let's take a look at an example of how to use the toString() method in JavaScript.

For example:

var totn_string = new String('TechOnTheNet');

console.log(totn_string);
console.log(totn_string.toString());

In this example, we have declared a string object called totn_string that is assigned the value of 'TechOnTheNet'. We have then invoked the toString() method of the totn_string variable to return a string representation of the object.

We have written the output of the string object as well as the toString() method to the web browser console log, for demonstration purposes, to show what the toString() method returns.

The following will be output to the web browser console log:

String {"TechOnTheNet"}
TechOnTheNet

In this example, the first output to the console log shows the String object. Whereas, the second output to the console log shows the primitive value or string representation of the object (which is 'TechOnTheNet').