Table of Contents
The JavaScript toString() method converts a variable (or a value) to a string. It is a built-in method for many data types, including numbers, arrays, dates, and objects.
The method is useful for:
When used on an array, toString() returns the array elements as a comma separated string.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript toString()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Array toString()</h4>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let myList = fruits.toString();
document.getElementById("demo").innerHTML = myList;
</script>
</body>
</html>

Result View Example
When used on a date, toString() returns a human-readable date and time string.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript toString()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Date toString()</h4>
<p id="demo"></p>
<script>
const d = new Date();
let text = d.toString();
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result View Example
When used on a number, toString() returns the number as a string.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript toString()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Number toString()</h4>
<p id="demo"></p>
<script>
let x = 123;
let text = x.toString();
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result View Example
Convert a number to a string, using base 2 (binary):
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript toString()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Number toString() with Base 2</h4>
<p id="demo"></p>
<script>
let x = 123;
let text = x.toString(2);
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result View Example
When used on a function, toString() returns the source code of the function as a string.
When used on an object, toString() an object returns "[object Object]". To provide a meaningful string representation, it can be overridden in the object definition:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript toString()</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>
<h4>Object toString()</h4>
<p id="demo"></p>
<script>
let person = {
firstname: "John",
lastname: "Doe",
}
let text = person.toString();
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Result View Example
Document in project
You can Download PDF file.