Tuesday, 2 April, 2019 UTC


Summary

Javascript Array ToString Example | Array.prototype.toString() Tutorial is today’s topic. The Array toString() method returns a string representing the specified array and its elements. Javascript toString() method converts an array into a String and returns the result.  For Array objects, the toString() method joins an array and returns one string that containing each array element separated by the commas.
Javascript Array ToString Example
The syntax of Javascript Array ToString() method is following.
array.toString()
Let’s take an example.
// app.js

let arr = ['krunal', 'ankit', 'rushabh', 'dhaval'];
console.log(arr.toString());
The output is following.
 
So, that means it has returned the comma separated values.
JavaScript calls a toString() method automatically when the array is to be represented as the text value or when the array is referred to in a string concatenation.
The returned string will separate the elements in the array with commas.
A slightly less common approach is to use the Javascript Array join() method. By default, it adds the comma to resulting values, though you can also specify that it adds nothing or some other separator value. Javascript Array join() method creates and returns the new string by concatenating all of the elements of an array.
You can also take advantage of JavaScript’s type coercion: the + operator can either add the two numbers or concatenate the two strings. But what happens when we try to join the object (the array [] is also the object) with something else? JavaScript is forgiving so it will not crash the program. Instead of that, it does know how to concatenate the strings so that it will convert everything into the string.
Convert Array of Arrays to String
We can also convert an array of arrays into a String. Let’s see the following example.
// app.js

let arr = [['krunal', 'ankit', ['hello']], ['rushabh', 'dhaval']];
console.log(arr.toString());
The output will be a single string with all the items comma separated. Notice that also, subarrays are separated by comma as well.
See the below output.
 
Finally, Javascript Array ToString Example | Array.prototype.toString() Tutorial is over.
The post Javascript Array ToString Example | Array.prototype.toString() Tutorial appeared first on AppDividend.