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.

Description

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.

Syntax

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

string.toString();

Parameters or Arguments

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

Returns

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

Note

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.

Example

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');

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

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"}
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’).