valueOf() in JavaScript

valueOf() in JavaScript | The valueOf() method of JavaScript returns the primitive value of a object. This method does not change the original value of a string. When you assign a string variable to another variable using an equals to(=) sign, the valueOf() method is internally invoked by JavaScript. 

Every object which is a descendant Object inherits the valueOf() method. Whenever a primitive value is needed, JavaScript uses the valueOf() method on its own and is very rarely used by programmers in their code.

const str = 'Hello World!';
const txt = str.valueOf();

The above example is equivalent to writing:

const str = 'Hello World!';
const txt = str;

If there is a primitive value linked to an object, it is returned via the function valueOf() { [native code] }() method. There is no primitive value for objects of type Object, therefore this function just returns the object itself.

But for objects of type Number, function valueOf() { [native code] }() delivers the fundamental numeric value that the item stands for. It also returns the string associated with a String object and the primitive boolean value associated with a Boolean object.

valueOf() JavaScript Example

const str = '999';
const txt = str.valueOf();
console.log(txt);
console.log(typeof(txt))

Output:-

999
string

JavaScript valueOf() method Example

const arr = [1, 2, 3, 4, 5, 6, 7];
const txt = arr.valueOf();
console.log(txt);
console.log(typeof(txt))

Output:-

[
1, 2, 3, 4,
5, 6, 7
]
object

As a JavaScript developer very rarely you will get chance to use the function valueOf() { [native code] }() function directly. Every time an object is used where a primitive value is anticipated, JavaScript performs this automatically.

In fact, it is challenging to distinguish between primitive values and their related objects due to this automatic activation of the function valueOf() { [native code] }() method. For instance, the typeof() method demonstrates the distinction between strings and String objects, but in actual JavaScript code, you can use both interchangeably.

These wrapper objects are reduced to their underlying primitive values via the function valueOf() { [native code] }() methods of the Number, Boolean, and String classes. When used with an integer, boolean, or string input, the Object() function Object() { [native code] } executes the opposite action: it wraps the primitive value in the appropriate object wrapper.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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