DEV Community

Cover image for Understanding valueOf() and toString() in JavaScript
tapuchandramojumder
tapuchandramojumder

Posted on

Understanding valueOf() and toString() in JavaScript

When working with objects in JavaScript, it's crucial to understand how they convert to primitive types, such as numbers or strings. This understanding becomes particularly important during operations like addition (obj1 + obj2) or when converting an object to a string (String(obj)). JavaScript provides two built-in methods, valueOf() and toString(), to handle these conversions.

Detailed Explanation:

valueOf() Method:

Purpose: Converts an object to a primitive numeric value.
Usage Scenario: JavaScript automatically invokes the valueOf() method when an operation requires a number, such as in arithmetic operations.
Customization: You can define a custom valueOf() method in your object to specify how it should convert to a number. If not defined, JavaScript uses the default method.

toString() Method:

Purpose: Converts an object to a string.
Usage Scenario: This method is called when JavaScript expects a string, like in string concatenation.
Customization: You can define a custom toString() method to control how your object converts to a string. If not defined, JavaScript uses the default method which typically returns "[object Object]".
Examples:



// Example of valueOf() method
const obj1 = {
value: 40,
valueOf() {
return this.value;
}
};

console.log(obj1 + 2); // Output: 42

// Example of toString() method
const obj2 = {
firstName: 'John',
lastName: 'Doe',
age: 30,
toString() {
return Name: ${this.firstName} ${this.lastName}, Age:
${this.age}
;
}
};`

console.log("Name: " + obj); // Output: "Name: John Doe, Age: 30"`

In these examples, we have objects obj1 and obj2. obj1 defines a custom valueOf() method that returns the numeric value 40. JavaScript automatically invokes the valueOf() method, resulting in the number 42.

obj2 defines a custom toString() method that returns a string representation of the person's name and age. JavaScript automatically invokes the toString() method, resulting in the string "Name: John Doe, Age: 30".

Summary:

JavaScript attempts to convert objects to the expected type (number or string) in operations. Defining valueOf() and toString() methods in your objects ensures that these conversions are predictable and aligned with your intentions.

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

The reality is slightly more complex... this is the default toPrimitive algorithm that JS uses:

toPrimitive

However, if an object has a method named with the well-known symbol Symbol.toPrimitive - then this will be run instead, allowing you to override the default behaviour shown above.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

An example of using Symbol.toPrimitive can be found in my experiment to add a range syntax to numbers:

Collapse
 
tapuchandramojumder profile image
tapuchandramojumder

nice article. I am totally agree with you. It's really hard to understand

Collapse
 
srinumeesala profile image
SRINUMEESALA

const obj={
name:undefined,
valueOf(){
return 5
},
age:30
}
const obj2={
name:"krishna",
toString(){
return "Radhe"
},
}
const obj3={
toString(){
return "Govind"
},
valueOf(){
return 5
},
age:30
}

console.log(obj+obj2)
console.log(obj+obj.age)
console.log(obj2+obj2.name)
console.log(obj3+obj2)

why valueOf have higher precedence than stringOf()?