JS: Introduction to Object Oriented Programming (OOP)
Theory: toString()
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]'.
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:
But if you define toString(), the code is simplified:
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:
The same can be done in the prototype of any constructor:
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:

