2

I have been using typeof operator to check if a variable is not defined like this:

if( typeof numLines === "undefined" ){
  // do something
}

But the same can be achieved using:

if( numLines === undefined ){
  // do something
}

As far as I remember, I had read somewhere that the typeof approach is better but now I think why should I use a slightly longer statement if there is no benefit at all in that. So my questions are:

  1. Is there really any benefit in sticking to typeof approach for such checks?
  2. Can you provide some examples where one approach is better than the other?

Thanks.

Mohit Bhardwaj
  • 9,650
  • 3
  • 37
  • 64

1 Answers1

1

According to a related question undefined is not assured to be the thing you expect it to be:

var undefined = 'uh oh'

if (numLines === undefined) {
  // Seems safe but isn't
}
else if (typeof(numlines) == 'undefined') {
  // Actually gets it.
}

It's very odd that undefined is not nailed down in JavaScript, but that's how it is with the ECMA standard.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • @AlexanderO'Mara I'm not sure that's a fix. That seems like clarification. – tadman Jun 09 '17 at 06:54
  • 1
    It's now only possibly with variable shadowing, as of ES5.1: https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.1.3 (the global undefined is immutable) – Alexander O'Mara Jun 09 '17 at 06:55
  • Hopefully someone, somewhere, will petition for a `defined()` function in JavaScript. Until then there's a reason to use things like Underscore. – tadman Jun 09 '17 at 06:56
  • Meh, the function name could just be shadowed. Then the same shadowing issue applies. – Alexander O'Mara Jun 09 '17 at 06:57
  • Having a dependable default would be a nice touch, but that's not how modern JavaScript seems to roll. – tadman Jun 09 '17 at 06:58
  • Thanks @tadman But if we assume that `undefined` was tempered with, same argument could go with `typeof` function itself that it might be redefined somewhere. Is it a possibility? – Mohit Bhardwaj Jun 09 '17 at 07:04
  • There's some things you can't monkey with in JavaScript, they're defined as [reserved keywords](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Reserved_keywords_as_of_ECMAScript_2015), and `typeof` is one of them. For reasons nobody has ever reasonably explained, `undefined` did not make this list. – tadman Jun 09 '17 at 07:07
  • Got it. Thanks a lot @tadman – Mohit Bhardwaj Jun 09 '17 at 07:10