JavaScript toString method is used to convert an array to a string. The array to be converted can contain any data, such as numbers, objects, strings, etc. It is usually used to converter numbers in strings.
The syntax of this method is very simple: array.toString().
The toString() method therefore returns a string.
Since the original array remains unchanged, so we store the result in a variable and then use the string obtained where needed.
JavaScript toString method can also be used to convert a number to a string, using this syntax: num.toString(base).
Where the base represents the system in which to translate.
We can also omit the base in order to simply get the decimal number in a string.
var number = 20;
console.log("String: " + number.toString());
But let’s make an example by specifying the base. Let’s convert a decimal number to binary:
var number = 20;
console.log("Binary : " + number.toString(2));
JavaScript toString – first example
Convert an array of numbers to a string using the toString() method.
So suppose we have the following array of numbers:
var numbers = [5,4,3,2,6,9,62];
We then use the toString method to convert the array and store the result in a variable such as a string name.
Finally we display the result in the browser console.
var stringNumbers = numbers.toString();
console.log(stringNumbers);
JavaScript toString – second example
The same could be done with an array of strings, so let’s repeat the example above by changing only the array.
For example, if we therefore have the following array:
var objectsSchools = ['pencil', 'eraser', 'sharpener', 'notebook', 'pencil'];
Then we apply the toString method to the array of starting strings and view the result for simplicity in the console.log.
var str = objectsSchools.toString();
console.log(str);
As in the previous example, once again we see a string in the console of our browser.
Conclusion
In this article we talked about the JavaScript toString method, in the next lesson we will tackle other methods with numerous examples.
[…] Prev lesson: toStringNext lesson: forEach […]