1

Found this in our code. What's the difference between:

if (typeof isValid === 'undefined') {

and

if (isValid === 'undefined') {

Why would anyone use the first one, I don't understand how this makes sense?

R. Kohlisch
  • 2,823
  • 6
  • 29
  • 59
  • 1
    if `isValid` is equal to `'undefined'` there's absolutely no way it has a type of undefined – apokryfos Sep 13 '19 at 12:00
  • The first one checks if `isValid` is `undefined`. The second checks if `isValid` has *the string value* `"undefined"` – VLAZ Sep 13 '19 at 12:01

2 Answers2

3

This:

if (typeof isValid === 'undefined') {

checks to see if the type of isValid is "undefined". It could be "undefined" because either A) isValid is a variable with the value undefined in it, or B) It's an undeclared identifier.

This:

if (isValid === 'undefined') {

checks to see if the variable isValid contains the string "undefined". The variable must exist (e.g., be declared), or a ReferenceError is thrown.

You see the first in situations where the author isn't sure the variable isValid has been declared, or because they're worried that undefined may have been redefined in the scope where the code occurs, or because a long time ago they were worried that the undefined in one realm (loosely: window/tab) and the undefined in another realm wouldn't be === to each other. (If that was ever true, it hasn't been for at least a decade.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Would you mind wielding your hammer on such questions? The kind of issue OP is facing has been raised many times before. – Kyll Sep 13 '19 at 12:02
  • I agree with @PaulStenne. Don't just try to gain more "reputation" with this kind of questions that were asked and answered before. – mindmaster Sep 13 '19 at 12:05
  • @PaulStenne - If someone points to a good dupetarget for it, yeah, absolutely and I do typically a dozen or more times a day. I don't know of a **good** dupetarget for this particular question, asking the difference between these particular two tests, but if you do please point it out and I'm happy to pile on. :-) (I don't think the current one is good at all, but I don't disagree enough to reopen either.) – T.J. Crowder Sep 13 '19 at 12:05
-2

if (typeof isValid === 'undefined') { means that you want to check if the variable has any value or not, whereas if (isValid === 'undefined') { means that you want to check if the variable has a string value 'undefined'

Shridhar Sharma
  • 2,337
  • 1
  • 9
  • 13