4

I'm learning Javascript by reading some code, but this function really puzzles me.

    hv:
        function(i) {
            var _this = this;
            return isArr(_this) ? _this.indexOf(i) > -1 : _this[i] !== void 0;
        }

This function is added to Object.prototype.
I don't quite get the void 0 at the end of the ternary expression. Can someone explain it to me?

Thanks.

octref
  • 6,521
  • 7
  • 28
  • 44

2 Answers2

6

The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

in this cases, the global variable undefined can be used instead: ie:

_this[i] !== undefined;

Jsfiddle Demo

suhailvs
  • 20,182
  • 14
  • 100
  • 98
2

void 0 is a way of getting undefined without fail. Some browsers allow overriding the undefined variable, but you can't override void

Zoey Mertes
  • 3,139
  • 19
  • 23