The valueOf method in JavaScript for strings serves the purpose of retrieving the primitive value of a String object. This method is automatically called by JavaScript, eliminating the need for explicit invocation within the code.
Syntax
The syntax for the valueOf method is expressed as follows:
Example
string.valueOf()
Returns
A string that denotes the fundamental value of a string object.
JavaScript String valueOf Method Example
Let us examine a few straightforward illustrations of the valueOf method.
Example 1
In this section, we will output the primitive value associated with a string object.
Example
<script>
var str="Example";
document.writeln(str.valueOf());
</script>
Output:
Output
Example
Example 2
Let us examine another example that demonstrates how to output the primitive value of a string object.
Example
<script>
var str=new String("Example");
document.writeln(str.valueOf());
</script>
Output:
Output
Example