JavaScript prototypes have a certain “magic method”, Object.prototype.toString()
. It's magic because it's called automatically whenever an object is used as a string. This happens regularly during development, we've all seen such output: '[object Object]'
.
const company = { name: 'Hexlet' };
company.toString(); // "[object Object]"
// Using an object in a string leads to an automatic call
console.log(`I love ${company}!`); // "I love [object Object]!"
What's it for? In web development, objects are often reduced to a string, for example when displaying them to the user or transferring data between different applications. Imagine a list of something, such as a list of courses on Hexlet. You can output the name of each course like this:
// React (JSX) syntax
<h2>{course.name}</h2>
// output
// <h2>Hexlet</h2>
But if you define toString()
, the code is simplified:
// React (JSX) syntax
<h2>{course}</h2>
// output
// <h2>Hexlet</h2>
The advantage here is the shorter notation and the fact that there are usually many different output options. We need to output to the log even when we're debugging. In all of these situations, having toString()
simplifies the work, because you don't need to convert objects to a string explicitly. In addition, in the future, it'll be enough to change precisely one part for the output to change in all places.
toString()
itself is nothing special; it's a common method in prototypes. And as such, we can redefine it:
const company = {
name: 'Hexlet',
toString() {
return this.name;
},
};
company.toString(); // "Hexlet"
console.log(`I love ${company}!`); // "I love Hexlet!"
The same can be done in the prototype of any constructor:
function Company(name) {
this.name = name;
};
Company.prototype.toString = function toString() {
return this.name;
}
const company = new Company('Hexlet');
console.log(`I love ${company}!`); // "I love Hexlet!"
But what if you want to display the object "as is"? This is needed to analyze the internal structure. If this object doesn't have toString()
, defined, we'll get a very uninformative output [object Object]
. In this case, you can convert the object to JSON:
const company = new Company('Hexlet');
// JSON is a string!
console.log(JSON.stringify(company)); // => '{"name":"Hexlet"}'
Recommended materials
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.