totn JavaScript

JavaScript: String valueOf() method

This JavaScript tutorial explains how to use the string method called valueOf() with syntax and examples.

Description

In JavaScript, valueOf() is a string method that is used to return the primitive value or string representation of an object. Because the valueOf() method is a method of the String object, it must be invoked through a particular instance of the String class.

Syntax

In JavaScript, the syntax for the valueOf() method is:

string.valueOf();

Parameters or Arguments

There are no parameters or arguments for the valueOf() method.

Returns

The valueOf() method returns the primitive value of the calling String object.

Note

  • The valueOf() method does not change the value of the original string.
  • You can also use the toString() method to return the string representation of an object.

Example

Let's take a look at an example of how to use the valueOf() method in JavaScript.

For example:

var totn_string = new String('TechOnTheNet');

console.log(totn_string);
console.log(totn_string.valueOf());

In this example, we have declared a string object called totn_string that is assigned the value of 'TechOnTheNet'. We have then invoked the valueOf() method of the totn_string variable to return a string representation of the object.

We have written the output of the string object as well as the valueOf() method to the web browser console log, for demonstration purposes, to show what the valueOf() method returns.

The following will be output to the web browser console log:

String {"TechOnTheNet"}
TechOnTheNet

In this example, the first output to the console log shows the String object. Whereas, the second output to the console log shows the primitive value or the string representation of the object (which is 'TechOnTheNet').