Description
The JavaScript String method valueOf()
returns the primitive value of a string, without changing the original string.
- It returns a new string and doesn't change the original string.
- It is commonly used to convert a string object to a primitive string.
- It is the default method for JavaScript strings and is used internally by JavaScript.
Syntax
The method valueOf()
has the below syntax, where str
is a string.
str.valueOf()
Parameters
The method valueOf()
doesn't allow any parameters.
Result
Returns the primitive value of a string, without changing the original string.
Example 1: Using the Method
The below example shows the basic usage of the method.
var str = "Hello World!";
var strObject = new String("Hello JavaScript!");
// Getting the value without the method - works the same as using the method
document.write(str); // Prints: Hello World!
// Getting the value of a string
document.write(str.valueOf()); // Prints: Hello World!
// Getting the value of a string object
document.write(strObject.valueOf()); // Prints: Hello JavaScript!
Output:
Hello World!
Hello World!
Hello JavaScript!
Overall
The JavaScript String method valueOf()
returns the primitive value of a string, without changing the original string.