Home » JavaScript

Array toString() method with example in JavaScript

JavaScript toString() method: Here, we are going to learn about the toString() method of array in JavaScript.
Submitted by IncludeHelp, on March 02, 2019

JavaScript toString() method

toString() method is used to convert an array to the string. It is called with the array name and returns the string containing array elements with comma separated.

Syntax:

    array.toString();

Parameters: None

Return value: A string containing array elements

Example:

    Input:
    var arr = [10, 20, 30, 40, 50];

    Function call:
    var str = arr.toString();    

    Output:
    str = "10,20,30,40,50"

JavaScript code to convert array’s elements to the string using Array.toString() method

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		var arr1 = ["Manju", "Amit", "Abhi", "Radib"];
		var arr2 = [10, 20, 30, 40, 50];
		var arr3 = [-10, -20, 0, 10, 20];
		
		var str1 = arr1.toString();
		var str2 = arr2.toString();
		var str3 = arr3.toString();
		
		document.write("str1: " + str1 + "<br>");
		document.write("str2: " + str2 + "<br>");
		document.write("str3: " + str3 + "<br>");
		
		document.write("printing the types of the objects...<br>");
		document.write("type of arr1: " + typeof(arr1) + "<br>");
		document.write("type of arr2: " + typeof(arr2) + "<br>");
		document.write("type of arr3: " + typeof(arr3) + "<br>");
		document.write("type of str1: " + typeof(str1) + "<br>");
		document.write("type of str2: " + typeof(str2) + "<br>");
		document.write("type of str3: " + typeof(str3) + "<br>");
	</script>
</body>
</html>

Output

str1: Manju,Amit,Abhi,Radib
str2: 10,20,30,40,50
str3: -10,-20,0,10,20
printing the types of the objects...
type of arr1: object
type of arr2: object
type of arr3: object
type of str1: string
type of str2: string
type of str3: string





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.