valueOf

Returns the primitive value of the specified object.

Applies to

Object

Syntax

valueOf()

Parameters

None

Description

Every object has a valueOf method that is automatically called when it is to be represented as a primitive value. If an object has no primitive value, valueOf returns the object itself.

You can use valueOf within your own code to convert an object into a primitive value, and you can create your own function to be called in place of the default valueOf method.

Every object type has a built-in valueOf method, which JavaScript calls whenever it needs to convert an object to a primitive value.

You rarely need to invoke the valueOf method yourself. JavaScript automatically invokes it when encountering an object where a primitive value is expected.

The following table shows object types for which the valueOf method is most useful. Most other objects have no primitive value.

Object Type

Value Returned by valueOf

Number

Primitive numeric value associated with the object.

Boolean

Primitive boolean value associated with the object.

String

String associated with the object.

Function

Function reference associated with the object. For example, typeof funObj returns object, but typeof funObj.valueOf() returns function.

You can create a function to be called in place of the default valueOf method. Your function must take no arguments.

Suppose you have an object type myNumberType and you want to create a valueOf method for it. The following code assigns a user-defined function to the object's valueOf method:

myNumberType.prototype.valueOf = new Function(functionText)

With the preceding code in place, any time an object of type myNumberType is used in a context where it is to be represented as a primitive value, JavaScript automatically calls the function defined in the preceding code.

An object's valueOf method is usually invoked by JavaScript, but you can invoke it yourself as follows:

myNumber.valueOf()

Tip:

Objects in string contexts convert via the toString method, which is different from String objects converting to string primitives using valueOf. All string objects have a string conversion, if only [object type]. But many objects do not convert to number, boolean, or function.