In JavaScript, the valueOf() method is used to retrieve the primitive value of a Number object. This method returns the underlying number value.
To demonstrate the usage of the valueOf() method, let’s consider an example:
const age = new Number(36);
typeof age; // object
age.valueOf(); // 36
In the given example, we create a Number object called age
with a value of 36. When we use the typeof
operator on age
, it returns “object” because age
is an instance of the Number object.
However, by using the valueOf() method on age
, we can retrieve the primitive value, which is 36 in this case.
It’s important to note that the valueOf() method is automatically called by JavaScript when a Number object needs to be converted to a primitive value, such as when using mathematical operations or when coercing the value to a string.
In conclusion, the valueOf() method provides a means to obtain the underlying number value from a Number object in JavaScript.
Tags: JavaScript, Number object, valueOf() method