1. Computing

valueOf and toString

By

Two methods that every single Javascript object has are valueOf() and toString().

The purpose of the valueOf() method is to convert the object into the most meaningful primitive value possible. The result of this will therefore be whatever makes the most sense out of a boolean value, number, or character string.

The purpose of the toString() method is to convert the object into the most meaningful character string.

As most objects make more sense converted into text rather than a boolean value or number, these two methods will return the same character string values for most object types. The most obvious exceptions where different values will be returned from the valueOf() and toString() methods are Boolean objects, Number objects, and Date objects. In the case of Date objects valueOf() will return a number representing milliseconds since 1/1/1970 while toString() will return an implementation dependent text representation of the date and time.

Most other object types will return the same value regardless of which of the two methods is used.

In some cases the text that is returned may be particularly useful. For example the value returned by both methods for an Array is a comma separated list of the arrays contents. This provides a quick and easy way of extracting the entire content of the array in one quick call. Another that probably will not have occurred to you is that each function that you define in your code is considered to be a Function object and the source code of the function can be quickly loaded into a variable using either of these methods.

  1. About.com
  2. Computing
  3. JavaScript
  4. Controls and Widgets
  5. Objects
  6. JavaScript - Methods valueOf and toString

©2014 About.com. All rights reserved.