JavaScript - toString() method

revision:


Category : object

The toString() method returns a string representing the object. This method is meant to be overridden by derived objects for custom type conversion logic.

Every JavaScript object has a toString() method. The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string.

Syntax :

        Object.toString()
    

Parameters: none

Examples:

            function Dog(name) {
                this.name = name;
            }
            const dog1 = new Dog('Gabby');
            Dog.prototype.toString = function dogToString() {
                return `${this.name}`;
            };
            console.log(dog1.toString());
            // Expected output: "Gabby"
        

Category : string

The toString() method returns a string as a string. The toString() method does not change the original string and can be used to convert a string object into a string.

Syntax :

        string.toString()
    

Parameters: none

Examples:

            <p>toString() returns the content of a string:</p>
            <p id="demo"></p>
            <script>
              let text = "Hello World!";
              let result = text.toString();
              document.getElementById("demo").innerHTML = result; 
            </script>
        

Category : array

The toString() method returns a string with array values separated by commas.The toString() method does not change the original array.

Syntax :

        array.toString()
    

Parameters: none

Examples:

            function sum(a, b) {
                return a + b;
            }
            console.log(sum.toString());
              // Expected output: "function sum(a, b) {
              //                     return a + b;
              //                   }"
            console.log(Math.abs.toString());
              // Expected output: "function abs() { [native code] }"
              
        

Category : function.prototype

The toString() method returns a string representing the source code of the function.

Syntax :

        function.toString()
    

Parameters: none

Examples:

            Function.prototype.toString.call('foo'); // TypeError
            var proxy = new Proxy(function() {}, {});
            Function.prototype.toString.call(proxy); // TypeError
        

Category : number

The toString() method returns a string representing the specified number value.

Syntax :

        toString()
        toString(radix)
    

Parameters:

radix : optional. An integer in the range 2 through 36 specifying the base to use for representing the number value. Defaults to 10. Must be an integer between 2 and 36. Base 2 is binary. Base 8 is octal. Base 16 is hexadecimal.

Examples:

            function hexColour(c) {
                if (c < 256) {
                  return Math.abs(c).toString(16);
                }
                return 0;
              }
              
              console.log(hexColour(233));
              // Expected output: "e9"
              
              console.log(hexColour('11'));
              // Expected output: "b"
              
        

Practical examples

example: using toString() method.

code:
                    <div>
                        <p id="string-1"></p>
                        <p id="string-2"></p>
                        <p id="string-3"></p>
                        <p id="string-4"></p>
                    </div>
                    <script>
                    const array1 = [1, 2, "a", "1a"];
                        console.log(array1.toString()); // "1,2,a,1a"
                        document.getElementById("string-1").innerHTML = "array : " + array1;
                        document.getElementById("string-2").innerHTML = "array to string: " + JSON.stringify(array1.toString());
                        const matrix = [
                            [1, 2, 3],
                            [4, 5, 6],
                            [7, 8, 9],
                        ];
                        console.log(matrix.toString()); // 1,2,3,4,5,6,7,8,9
                        document.getElementById("string-3").innerHTML = "matrix : " + matrix;
                        document.getElementById("string-4").innerHTML = "matrix to string: " + JSON.stringify(matrix.toString());
                    </script>
                

example: get the value of a string object.

toString() returns the content of a string object:

code:
                    <div>
                        <p>toString() returns the content of a string object:</p>
                        <p id="string-5"></p>
                    </div>
                    <script>
                        let text = new String("Hello World!");
                        let result = text.toString();
                        document.getElementById("string-5").innerHTML = result; 
            
                    </script>
                

example: get the content of a text.

code:
                    <div>
                        <p id="string-6"></p>
                        <p id="string-7"></p>
                        <p id="string-8"></p>
                    </div>
                    <script>
                        let text1 = "Hello World!";
                        document.getElementById("string-6").innerHTML = "original text : " + text1;
                        let result1 = text1.toString();
                        document.getElementById("string-7").innerHTML = "text toString(): " + result1; 
                        let result2 = text;
                        document.getElementById("string-8").innerHTML = "text: " + result2; 
                    </script>
                

example: array to string

code:
                    <div>
                        <p id="string-9"></p>
                        <p id="string-10"></p>
                    
                    </div>
                    <script>
                        const fruits = [" Banana", " Orange", " Apple", " Mango"];
                        document.getElementById("string-9").innerHTML = "original array : " + fruits;
                        let text2 = fruits.toString();
                        document.getElementById("string-10").innerHTML = "after toString() : " + text2;
                    </script>
                

example: getting source text of a function.

code:
                    <div>
                        <p id="string-11"></p>
                        <p id="string-12"></p>
                    </div>
                    <script>
                        function foo() {
                            return "bar";
                        }
                        console.log(`${foo}`);
                        // function foo() {
                        //   return "bar";
                        // }           
                        document.getElementById("string-11").innerHTML = "function : " + `${foo}`;
            
                        function boo /* a comment */() {
                            return "bar";
                        }
                        console.log(boo.toString());
                        // function boo /* a comment */() {
                        //   return "bar";
                        // }
                        document.getElementById("string-12").innerHTML = "function : " + `${boo}`;
                    </script>
                

example: using toString() method.

code:
                    <div>
                        <p id="string-13"></p>
                        <p id="string-14"></p>
                        <p id="string-15"></p>
                        <p id="string-16"></p>
                        <p id="string-17"></p>
                        <p id="string-18"></p>
                        <p id="string-19"></p>
                    </div>
                    <script>
                        const count = 10;
                        console.log(count.toString()); // "10"
                        console.log((17).toString()); // "17"
                        console.log((17.2).toString()); // "17.2"
                        document.getElementById("string-13").innerHTML = "count.toString() : " + count.toString();
                        document.getElementById("string-14").innerHTML = "(17).toString() : " + (17).toString();
                        document.getElementById("string-15").innerHTML = "(17.2).toString() : " + (17.2).toString();
            
                        const x = 6;
                        console.log(x.toString(2)); // "110"
                        console.log((254).toString(16)); // "fe"
                        console.log((-10).toString(2)); // "-1010"
                        console.log((-0xff).toString(2)); // "-11111111"
                        document.getElementById("string-16").innerHTML = "(x.toString(2) : " + x.toString(2);
                        document.getElementById("string-17").innerHTML = "((254).toString(16) : " + (254).toString(16);
                        document.getElementById("string-18").innerHTML = "((-10).toString(2) : " + (-10).toString(2);
                        document.getElementById("string-18").innerHTML = "((-0xff).toString(2) : " + (-0xff).toString(2);