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(): string

This 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,

  1. Create a String object strObj with the value 'Hello World'.
  2. Use valueOf() to get the primitive string value of the object.
  3. Store the result in primitiveStr.
  4. Log primitiveStr to 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,

  1. Create a String object strObj with the value 'Hello'.
  2. Create a primitive string primitiveStr with the value 'Hello'.
  3. Use valueOf() on strObj to get its primitive value.
  4. Compare the primitive value of strObj with primitiveStr using === 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,

  1. Create a String object strObj with the value 'World'.
  2. Concatenate strObj with a primitive string 'Hello '.
  3. 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.