• JavaScript Video Tutorials

JavaScript String valueOf() Method



The JavaScript String valueOf() method returns the primitive value of the given string as a string data type. It does not change the original string but returns a new string. This method can also be used to convert a String object into a primitive string if needed by invoking the valueOf() method on a String object reference variable.

This is a default method of JavaScript String, and it is usually called internally by JavaScript.

Syntax

Following is the syntax of JavaScript String valueOf() method −

valueOf()

Parameters

  • It does not accept any parameters.

Return value

This method returns a primitive value of the given string.

Example 1

In the following program, we are using the JavaScript String valueOf() method to retrieve the primitive value of the current string "Tutorials Point".

<html>
<head>
<title>JavaScript String valueOf() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("Original string: ", str);
   document.write("<br>The str.valueOf() method returns: ", str.valueOf());
</script>    
</body>
</html>

Output

The above program returns "Tutorials Point".

Original string: Tutorials Point
The str.valueOf() method returns: Tutorials Point

Example 2

The following is another example of the JavaScript String valueOf() method. In this example, we are trying to invoke this method on a String object (new String("Hello World")) reference variable to convert it into a string.

<html>
<head>
<title>JavaScript String valueOf() Method</title>
</head>
<body>
<script>
   let strObj = new String("Hello World");
   document.write("StrObj: ", strObj); // valueOf() method called internally here
   console.log(strObj); // returns [[PrimitiveValue]]:"Hello World"
   document.write("<br>The strObj.valueOf() method returns: ", strObj.valueOf());
</script>    
</body>
</html>

Output

After executing the above program, it will return a new string "Hello World".

StrObj: Hello World
The strObj.valueOf() method returns: Hello World
Advertisements