Thursday, July 21, 2011

"toString" method in JavaScript

Every object in JavaScript has 'toString' method by default. This method returns the representation of that object in string format. If you have ever called alert on an object in mistake, you would have come across this message in alert box  '[object, Object]'. Actually when you put alert on object itself, it is assumed that you want to see the internal representation of the object and its 'toString' method is invoked which returns the default string for any object as mentioned before.
So what if  you want to make your object representation more meaningful or let say you want to debug your code and just put alert here and there and wants to see what your object looks like at different point of time. Here comes overriding 'toString' method. C#/VB.NET developers, remember yourself overriding toString method of base class "Object". This is exactly similar to that.
Let me take an example as following

function Employee(name, age, company) {
    this.employeeName = name;
    this.age = age; = company;
    this.toString = function () {
        return "Employee " + this.employeeName + " of age " + this.age + 
" working in " +;
What I am doing here is basically forming a meaningful string from my Employee object properties. Now let me put an alert on employee object.

    <script language="javascript" type="text/javascript">
          window.onload = function () {
            var e = new Employee("Abhishek""30""abcSoftware");

When I run this code, on my window onload I get following popup.

As I said before, I can use this method for debugging purposes or in general conveying a better representation of my object (for e.g. if you are writing a JS library, you would like your users to get a meaningful message while putting an alert on your objects, won't you?)
Note: If you put alert on function name itself for e.g. alert(Employee), it would be 'toString' method of function type that will be called and it will print your entire function in the alert box. Try that.
Thanks for reading.

No comments:

Post a Comment