Sometimes it may be necessary to convert a value to a string. In such cases the toString() method will be useful. In general, there are several ways to convert a value to a string, but let's start with toString().

The toString() method is a property of the Object prototype object, it is a method of this object. The interpreter calls it whenever it needs to convert an object to a string. For example, this can be observed when we add a string to an object, or when passing an object to a method that requires a string. So, by default, the toString() method is inherited by every object descended from class Object.

In addition to the fact that the toString() method can convert an input value, it can also combine all elements of an input array into one string value. By the way, these output elements of the array will be separated by a comma.

It should be added that the toString() method is generalized, so it can be used with any object.

Syntax

array.toString()
array.toString(base)

We can see that the method can be called both with one parameter and without it. This optional parameter determines which numeric basis the input number is represented by. This integer ranges from 2 to 36, which is used to determine the basis for representing numerical values.

Return value

You might think that the method only returns strings as a result. Not quite so. In fact the method can return any primitive data type as a result. For example, this could be a number, string, boolean, null, undefined і symbol data type.

If it is necessary, we can call this method for an empty array. What result will we get in this case? An empty string. And if an array element is undefined, or null, it will be converted to an empty string.

All objects, including built-in ones, have their own implementations of the toString() method. For example, for arrays the method is able to display a list of elements through a comma, for dates the method displays the date as a string, for a function the method outputs the function code.

Examples

By using base parameters we can convert 10 base numbers to other base numbers. Let's look at the example below where we are converting a base decimal number to a binary number.

const value = 12;
value.toString(2);  // 1100 as a result

Let's see if this will work for slightly larger numbers:

const value = 123;
value.toString(2);  // 1111011 as a result

As we can see, this also works. We can conclude that if we specify something else instead of the binary system, the function will also be rationally used.

We have already mentioned that it is not necessary to pass a parameter to a method. What do we get in this case?

const value = 123;
value.toString(); // 123

It is seen that the number is converted to a string without changing the base parameter. Such a recording option is still possible:

(12).toString();  // 12

Аctually in these above examples we see that the method is able to rotate not only string values, but also numerical values. In the following example we declare an array with different values. as a result we get values through commas, except those that are undefined or null:

const y = [undefined, null, 10, 0, 32, null];
y.toString();   // ",,10,0,32,"

And here let's declare an empty array:

const z = [];
z.toString();   // "" as a result

Okay, now let's move on to a little more complex structure. It is possible to create an individual function to call toString(). The method does not accept arguments and must return a string. It can have any value, but it will be most useful if it carries information about the object.

Let's describe a human via basic inputs:

class Person(name, surname, sex, age, nationality)
{
  this.name = name;
  this.surname = surname;
  this.sex = sex;
  this.age = age;
  this.nationality = nationality;
}
const thePerson = new Person('Kate', 'Smith', 'female', 25, 'American');
 
Person.prototype.toString = function personToString()
{
    return `Person: ${this.name}  ${this.surname}, sex - ${this.sex},
     age - ${this.age} years old, nationality - ${this.nationality}`;
}
//  Person: Kate Smith, sex - female, age -25 years old, nationality - American

There are many ways to use toString() and many examples to explain how the function works, but it is recommended to use it only as a tool for metaprogramming or debugging. Having this method in the business logic of an application will sooner or later lead to errors in some cases.

Other methods

Speaking of toString() we can not omit other ways to transform a string. In addition to the method we have already considered, there are other ways of converting a string. In general note the following ways:

" " + value
String(value)

It is clear that if we have several ways to do something, some of them may be better, others worse. 0.toString() does not work if the input values ​​are zero or indeterminate. However, methods ""+value and String(value) can easily handle this.

The ""+value method will be most useful if the input value you want to convert is surrounded by non-empty strings. However, this method will not be optimal if you want to convert a value to a string.

The String(value) method is clearly defined: it must be applied to the value. Although, in some programming languages ​​such a function call looks the same as the constructor. So programmers may confuse two lines that look almost the same, but run differently.

Note that both ""+value and String(value) convert their input value into a string using the toString() method.

toString() and valueOf()

In conclusion, JavaScript's type system is not perfect, i.e. it allows us to mix different data types, and performs many operations implicitly.

In converting, toString() works in tandem with valueOf() to reduce the object to the primitive it needs to operate on. For example, the addition operator turns into concatenation if there is at least one string among the operators. Also certain standard language functions convert an argument to a string.

valueOf() is used to numerically convert an object (concatenation of numbers and strings). But not all objects have it (that is, they do, but it returns the object itself, therefore it is ignored) and must return a primitive, otherwise it will be ignored and toString() will be called.

toString() is used for string converting an object. All objects already have this method, although sometimes it is not informative. Also it is obliged to return the primitive.

If, for example, we need to add two objects, the Add Operator first checks whether these two objects are primitives. In other words, the valueOf() method is called. Then the toString() method is not called because the overridden valueOf()method for the object returns a primitive value. That is, toString() will be applied to the result we get after the valueOf() method, but not to the source object.

In general, the purpose of valueOf() is to obtain a primitive value associated with an object. If the object does not have a basic primitive value, the object is simply returned. The purpose of toString(), on the other hand, is to return a string representation of an object.