TypeScript String valueOf()
Syntax & Examples
String.valueOf() method
The valueOf() method returns the primitive value of a String object. This method is usually called internally by JavaScript and not explicitly in code.
Syntax of String.valueOf()
The syntax of String.valueOf() method is:
valueOf(): stringThis valueOf() method of String returns the primitive value of the specified object.
Return Type
String.valueOf() returns value of type string.
✐ Examples
1 Using valueOf() to get the primitive value of a string object
The valueOf() method can be used to retrieve the primitive value of a String object.
For example,
- Create a String object
strObjwith the value 'Hello World'. - Use
valueOf()to get the primitive string value of the object. - Store the result in
primitiveStr. - Log
primitiveStrto the console.
TypeScript Program
const strObj = new String('Hello World');
const primitiveStr = strObj.valueOf();
console.log(primitiveStr);Output
'Hello World'
2 Comparing String object and primitive string using valueOf()
The valueOf() method can be used to compare a String object with a primitive string.
For example,
- Create a String object
strObjwith the value 'Hello'. - Create a primitive string
primitiveStrwith the value 'Hello'. - Use
valueOf()onstrObjto get its primitive value. - Compare the primitive value of
strObjwithprimitiveStrusing===and log the result.
TypeScript Program
const strObj = new String('Hello');
const primitiveStr = 'Hello';
console.log(strObj.valueOf() === primitiveStr);Output
true
3 Using valueOf() in string concatenation
The valueOf() method can be implicitly used in string concatenation.
For example,
- Create a String object
strObjwith the value 'World'. - Concatenate
strObjwith a primitive string 'Hello '. - Log the concatenated result to the console.
TypeScript Program
const strObj = new String('World');
const result = 'Hello ' + strObj;
console.log(result);Output
'Hello World'
Summary
In this TypeScript tutorial, we learned about valueOf() method of String: the syntax and few working examples with output and detailed explanation for each example.