JavaScript toString()

Back to JS page

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:

JavaScript Array toString()

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>

Example 1

Result View Example

JavaScript Date toString()

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>

Example 2

Result View Example

JavaScript Number toString()

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>

Example 3

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>

Example 4

Result View Example

JavaScript Function toString()

When used on a function, toString() returns the source code of the function as a string.

JavaScript Object toString()

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>

Example 5

Result View Example

Document

Document in project

You can Download PDF file.

Reference