What is the toString method of the strings class in JavaScript?

In Javascript, we can use the toString method to get the string representation of an object.

Note: This function is equivalent to the valueOf() method.

Syntax

toString();

Parameters

This function doesn’t need any parameters.

Return value

This function will return a string that represents a String object.

Note: every string in JavaScript is an object as well.

Code

var ourstring = new String("Hello, Educative!");
let int1 = BigInt(234);
console.log(ourstring, int1);
console.log(ourstring.toString(), int1.toString());
console.log("Hello, Educative!".toString()); // a string is also a string object
console.log("Hello, Educative!".toString() == ourstring.valueOf()); // these methods are equivalent

Explanation

  • In lines 1 and 2, a String object with the value "Hello, Educative!" is created and a BigInt with a value of 234.
  • In lines 4 and 5, the difference is shown between printing ourstring and int1 as their respective objects and then their string representation, using toString().
  • Line 7 shows how the result of using toString() is equivalent to using valueOf().

Free Resources