JavaScript valueOf() String method is used to get the primitive value of the string object. You don’t need to use it in your code because it is invoked by JavaScript automatically.
string.valueOf()
JavaScript valueOf() example
A simple example code gets the value of a text:
<!DOCTYPE html>
<html>
<body>
<script>
let text = "Hello World!";
let result = text.valueOf();
console.log(result)
console.log(typeof(result))
</script>
</body>
</html>
Output:
More example
function MyNumberType(n) {
this.number = n;
}
MyNumberType.prototype.valueOf = function() {
return this.number;
};
const object1 = new MyNumberType(4);
console.log(object1 + 3);
// expected output: 7
Do comment if you have any doubts or suggestions on this Js string method tutorial.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version