Purpose of the valueOf() Function

Let me start off by explaining the commonly misunderstood valueOf() function. The purpose of this function is to return a primitive which represents the specified object. Why is this necessary? Let’s use the following code to illustrate why:

var objNum = new Number(1048576);
var num = objNum.valueOf();
alert('objNum is of type "' + (typeof objNum) + '"');
alert('num is of type "' + (typeof num) + '"');

If you were to execute this code, what do you think would be displayed by the first alert? What about the second alert? Believe it or not, the first alert will display the following:
objNum is of type "object"

On the other hand, the second alert will display this:
num is of type "number"

Using instanceof For Object Detection

What about using instanceof? Do you think both objNum and num will be reported as instances of the Number object?

var objNum = new Number(2097152);
var num = objNum.valueOf();
alert(objNum instanceof Number);  // true
alert(num instanceof Number);  // false

Believe it or not, if you run the code above, the first alert will show true while the second will show false. The reason the second evaluates to false is because num is a primitive and not an instance of the Number object.

Properties for Primitives & Objects

Does the fact that a primitive is not an instance of an object mean that primitives don’t have access to the same prototypal properties and functions that objects have access to? Let’s find out:

// Define the object and the primitive:
var objNum = new Number(4194304);
var num = objNum.valueOf();

// Add a property to each number object?
Number.prototype.isNumberInstance = true;

// Show the alerts:

Believe it or not, both alerts will display the word true indicating that the isNumberInstance is defined for both number objects and primitives. This proves that the same prototypal members that are attached to objects are also attached to primitives in JavaScript.

Testing Types for Primitives & Objects

Since the same properties and functions apply to both primitives and their equivalent objects, how can we test either a primitive or object to determine whether or not it is a number? The following code shows how to do so for numbers:

// Indicates whether or not the specified parameter is a number.
function isNumber(param) {
  return Object.prototype.toString.call(param) == "[object Number]";

// Define the object and the primitive:
var objNum = new Number(1073741824);
var num = objNum.valueOf();

// Show the alerts:

If you run the above code, you will find that isNumber() returns true for both primitives and objects. As you may have already figured out, using the Object.prototype.toString() function will allow us to see the type of the specified object. This is one of the techniques that I am using in the next version of jPaq to do type quick checking.

Categories: BlogJavaScriptJScript

Leave a Reply

Your email address will not be published. Required fields are marked *