Question

I'm working on a project where Array prototype has new method added:

Array.prototype.addOrRemove = function(value) {
    var index = _.indexOf(this, value);

    if (index === -1) {
        this.push(value);
    } else {
        this.splice(index, 1);
    }
    return this;
};

It either adds new value (if it's not present in the array) or removes it (otherwise). The strange thing is that when I type:

console.log([]);

I get the following output (in the chrome JS console):

[addOrRemove: function]

I thought that only values should be present in such console log. Did I do something wrong or is it a normal behavior (seems strange anyway)? I'd appreciate some explanation.

Was it helpful?

Solution

You could use defineProperty, which by default makes a property non-enumerable.

Object.defineProperty(
    Array.prototype,
    'addOrRemove',
    {
        get: function() {
            return function(value) {
                var index = _.indexOf(this, value);

                if (index === -1) {
                    this.push(value);
                } else {
                    this.splice(index, 1);
                }
                return this;
            };
        }
    }
);

console.log([]);

http://jsfiddle.net/qHFhw/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top