0

I was looking at this question: Check if an object is defined: best practice and noticed an answer with something I haven’t seen before:

function isDefined(x) {
    var undefined;
    return x !== undefined;
}

What would be the reason to declare undefined and leave it not defined — in other words define undefined as undefined?

Community
  • 1
  • 1
James Bruckner
  • 909
  • 7
  • 10

1 Answers1

11

Some people are convinced that using undefined directly is bad because someone could do window.undefined = "whatever". This is because, in ES5 and before (we'll see what comes later), undefined is not a reserved word and can be used as an identifier.

The local var prevents such a bad global variable poisoning - it introduces a local variable called "undefined" (which will shadow any bad variable that may exist) who's value defaults to the real undefined value because there is no assignment.

If I was so concerned (which I am not), I would do x !== (void 0). Unlike undefined, the void operator has always been a reserved word and so it is immune to aforementioned poisoning.

user2246674
  • 7,621
  • 25
  • 28
  • Awesome answer with an explanation of a simpler alternative, Thanks! Give me 7 minutes and I'll make it as accepted. – James Bruckner Sep 06 '13 at 00:03
  • `typeof foo !== 'undefined'` is another option. – Matt Sep 06 '13 at 00:05
  • 1
    @Matt Indeed another idiom that is used a good bit. I *usually* just do `foo !== undefined` if I need such strict check as I find it simpler and it avoids the urge to allow "undeclared variables". In any environment for which `undefined === void 0` is not true, I wave my hands and walk away as additional (valid) assumptions may also be invalidated. – user2246674 Sep 06 '13 at 00:08