Array.prototype.toString

This is one of my favorite javascript tricks, because of its effort-to-payoff ratio.

Problem: the default Array.prototype.toString hides any nested structure.

[1, 2, 3, 4, 5].toString(); //-> "1, 2, 3, 4, 5"
[1, 2, [3, 4], 5].toString(); //-> "1, 2, 3, 4, 5"

Solution: override Array.prototype.toString.

Array.prototype.toString = function() {
    return '[' + this.join(', ') + ']';
};

[1, 2, 3, 4, 5].toString(); //-> "[1, 2, 3, 4, 5]"
[1, 2, [3, 4], 5].toString(); //-> "[1, 2, [3, 4], 5]"
Advertisements

4 thoughts on “Array.prototype.toString

  1. Overriding is my favorite in any language, but you should consider a better example to show it for toString() in JS?

    [‘1’, ‘2’, ‘[3, 4]’, ‘5’].toString() does the job effortlessly.

  2. Shaurya, your example only works because you manually .toString()’d the [3,4], putting '[3, 4]' (a string) into the root array. If I’d changed Array.toString() to use a lispy style, like this:

    Array.prototype.toString = function() {
        return '(' + this.join(' ') + ')';
    };
    

    …then your example would return '(1 2 [3, 4] 5)', which isn’t what’s intended.

    The thing that makes this trick work is that it’s recursive, so it’ll correctly show an array that’s nested at any level. For example, the default:
    [[[[[[[[[1]]]]]]]]].toString(); //-> '1'
    …with the above addition:
    [[[[[[[[[1]]]]]]]]].toString(); //-> '[[[[[[[[[1]]]]]]]]]'

Comments are closed.