Home » Programming » Javascript » Javascript Tostring

The JavaScript toString() Method, Explained + Examples

One of the most common things you will want to do with a variable is to print a string representation of it. That’s what the toString() method is for. This article will explain when and how you can use it.

Converting to Strings

Data is displayed on your computer screen is most frequently displayed as text strings, regardless of how the data was stored. Numbers, arrays, boolean values, and objects, all have string representations that allow them to be viewed as text on screen, either for the user to read or for debugging purposes.

Different methods are used to convert non-string values to strings for display, depending on the type of the variable being converted to a string.

Conversion vs Coercion

Before we explore these methods, it’s worth nothing that there are two ways a variable may be converted to a string, without the toString() method being called directly.

Type Conversion is the explicit conversion of a variable to a string:

var myString = String(MyVariable);

This is done by explicitly calling the String() constructor to create a new String variable from the given parameter.

Type Coercion is the implicit (automatic) conversion of a variable to a string:

var myString = myVariable + "hello";

Coercion occurs when a variable must be converted to a string to perform the given task – in this case, as a variable is being joined with a string (using the + operator), it will be automatically converted to a string to allow for it to be joined to “hello”.

Coercion is a “feature” of JavaScript which is not present in many other programming languages, so some programmers choose to use explicit conversion wherever possible to make it clear to the reader how they expect a variable to be treated.

The toString() Methods

Regardless of whether explicit or implicit conversion is occurring, the toString() method of a variable is called to generate the string representation of the variable. Directly calling the toString() method looks like this:

var myString - myVariable.toString();

Depending on the type of variable toString() is called on, different behavior is expected.

JavaScript’s Built in Types

JavaScript’s built in types (NumberBigintStringObject/ArrayBoolean) all have their own toString() methods. Here’s how each one behaves.

Note: null and undefined types do not have any attached methods.

Numerical Variables (Number and BigInt)

Calling the toString() method of a Number type variable in JavaScript will return a string representation of the number.

var myNumber = 6.5;
var myString = myNumber.toString(); // "6.5" - a string representation of the provided number

An optional radix can be supplied to specify the base for use when representing the numerical value. The radix must be between 2 and 36.

var myNumber = 5;
var myString = myNumber.toString(2); // "101" - the string representation was generated using the supplied radix of 2

Being able to supply the radix is possible using explicit or implicit type conversion, and is only available by calling the toString() method of a number variable directly.

The same behavior applies to the BigInt variable type.

Strings

Calling the toString() method of a String variable does pretty much what you’d expect it to – it returns a copy of the unmodified original string.

var myString = "Hello!";
var myNewString = myString.toString(); // "Hello!"

Boolean Values

The Boolean object toString() method returns either “true” or “false”.

var myBoolean = false;
var myString = myBoolean.toString(); // "false"

Boolean values can only take a true or false value.

Arrays

The toString() method can also be used to view a string representation of JavaScript arrays.

var myArray = ['dog', 'fish", 'cat'];
var myString = myArray.toString(); // "dog,fish,cat"

The default behavior for the toString() method in JavaScript arrays is to return each element in the array’s own string representation (as provided by calling the toString() method of each element), separated by a comma.

Dates

The toString() method of Date objects will return information about the data and time stored, including day of the week, timezone, and the full date/time in a single string.

var myDate = new Date();
var myString = myDate.toString(); // "Mon Feb 07 2022 20:56:24 GMT+1030 (Australian Central Daylight Time)"

Functions

JavaScript Functions are in themselves objects, and have their own toString() method which returns a string containing the complete source code of the function.

function sayHi(){
    console.log('Hi!');
}
var myString = sayHi.toString(); 
// "function sayHi(){
//    console.log('Hi!');
// }"

Custom Objects/Classes and Overriding toString()

JavaScript Objects also have a toString() method. Unfortunately it’s default implementation isn’t all that useful:

var myObject = {name:'bob'};
var myString = myObject.toString(); // "[object Object]"

Above, a generic object is declared, and it’s toString() method called. The only information included in the generated string is “[object Object]” – telling us that the variable is an object of class Object. Not useful, and this is the default behavior for all objects – an object of class Fruit will have a string representation of “[object Fruit]”, for example.

class Fruit {
    constructor(name) {
        this.name = name
    }
    toString() {
        return this.name;
    }
}

var myFruit = new Fruit('Apple');
var myString = myFruit.toString(); // "Apple"

Above a JavaScript Class called Fruit is created, which accepts a name as a parameter. In the declaration for the Fruit class, a toString() method is defined which returns the name attribute of the fruit. This toString() method overrides the default one.

Thus, instead of the default toString() method for objects of the Fruit class returning “[object fruit]”, the custom one is called, returning the name of the fruit itself (in the above case, “Apple”).

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment