JS TutorialLesson #107

JavaScript toString()

The JavaScript toString() method converts a variable (or a value) to a string.

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:

  • Converting data to a readable format for display
  • Ensuring type compatibility when a string is required
  • Customizing objects other user interfaces
  • Customizing objects for debugging

Share

JavaScript Array toString()

When used on an array, toString() returns the array elements as a comma separated string.

Example

Example Code

javascript
Try it Yourself
const fruits = ["Banana", "Orange", "Apple", "Mango"];

let myList = fruits.toString();

JavaScript Date toString()

When used on a date, toString() returns a human-readable date and time string.

Example

Example Code

javascript
Try it Yourself
const d = new Date();

let text = d.toString();

JavaScript Number toString()

When used on a number, toString() returns the number as a string.

Example

Example Code

javascript
Try it Yourself
let x = 123;

let text = x.toString();

Convert a number to a string, using base 2 (binary):

Example

Example Code

javascript
Try it Yourself
let x = 123;

let text = x.toString(2);

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:

Example

Example Code

javascript
Try it Yourself
let person = {

  firstname: "John",

  lastname: "Doe",

}

let text = person.toString();

Interactive Code Examples

JS Example 1

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const fruits = ["Banana", "Orange", "Apple", "Mango"];



let myList = fruits.toString();

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
const d = new Date();



let text = d.toString();

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let x = 123;



let text = x.toString();

JS Example 4

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let x = 123;



let text = x.toString(2);

JS Example 5

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let person = {

  firstname: "John",

  lastname: "Doe",

}

let text = person.toString();