Using String toString() method to coding in Javascript/JS

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


In JavaScript, toString() is a string method that is used to return a string illustration or primitive fee of an object. Because the toString() technique is a technique of the String object, it ought to be invoked through a precise occasion of the String class.


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


Parameters or Arguments

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


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


The toString() technique does no longer trade the fee of the original string. You can additionally use the valueOf() technique to return the primitive fee of a String object.


Let’s take a appear at an instance of how to use the toString() method in JavaScript.

For example:

var totn_string = new String('TechOnTheNet');


In this example, we have declared a string object referred to as totn_string that is assigned the cost 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 properly as the toString() method to the web browser console log, for demonstration purposes, to exhibit what the toString() method returns.

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

String {"TechOnTheNet"}

In this example, the first output to the console log indicates the String object. Whereas, the 2d output to the console log shows the primitive cost or string representation of the object (which is ‘TechOnTheNet’).