Sunday, 30 September 2018

JavaScript: toString method

toString() method is used to get the string representation of any object. JavaScript provides default implementation of toString method.

var arr1 = [2, 3, 5, 7, 11];
document.write(arr1);

Above statement prints the data like ‘2,3,5,7,11’ (write method calls the toString method of object internally).

It is always good to define toString method for custom objects.

toString.html
<!DOCTYPE html>

<html>

<head>
    <title>toString Example</title>
</head>

<body>
    <script type="text/javascript">
        var employee = {
            firstName: "Hari Krishna",
            lastName: "Gurram",
            id: 123,

            toString: function() {
                return "[firstName = " + this.firstName + ", lastName = " + this.lastName + ", id = " + this.id + "]";
            }
        }

        document.write(employee);
    </script>
</body>

</html>
Open above page in browser, you can able to see following message.

[firstName = Hari Krishna, lastName = Gurram, id = 123]




Previous                                                 Next                                                 Home

No comments:

Post a Comment