1

I looked at this issue:

How to determine if variable is 'undefined' or 'null'?

But it did not help.

I have the following code:

    if (_modeID != 8 && _modeID != 9)
        // do something

_modeID is defined and assigned a value in a separate file all together.

I'm encountering a bug where, for some reason, var _modeID = someIntVal; is never executed, so when the if statement above runs there is no _modeID at all.

I expanded it to be if (_modeID === null || _modeID === undefined || (_modeID != 8 && _modeID != 9) but this still throws the following error:

ReferenceError - Java Script Error : '_modeID' is undefined

I was hoping that either the first or second condition would evaluate to true in this case but apparently not. Can anyone shed some light as to what I'm doing wrong?

Is var _modeID = undefined; if (_modeID === undefined) ... not the same as simply if (_modeID === undefined) ... assuming those two snippets were "complete" files?

Community
  • 1
  • 1
sab669
  • 3,574
  • 4
  • 29
  • 64
  • 1
    [Use `typeof`](https://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized) if you really want to tell whether `_modeID` is defined, but the real question you should be asking is **why** the other statement that defines it isn't running, and you haven't actually posted enough code for us to diagnose that problem. – meager Sep 23 '16 at 15:44
  • Can you talk more about this separate file where _modeID is defined? Can you show its definition? I suspect it may be in function scope somewhere else. – sma Sep 23 '16 at 15:44
  • `_modeID` is defined in a .cshtml Razor View file like so: `var _modeID =@Model.IntMode`. We have a page which lists reports (which creates / sets this value), or a Search page to find a report. If they use the Search page, that variable doesn't get created because it takes them directly to the report rather than the page which lists the reports. Honestly it's really *not* a problem; the variable is literally only used in that single check in my question. The value is not used anywhere else. – sab669 Sep 23 '16 at 16:56

1 Answers1

5

I generally see people check the type of the variable instead of the variable itself, i.e.

if( typeof _modeID === 'undefined' ) {
  ...
}
Jeff Jenkins
  • 15,356
  • 6
  • 46
  • 86
  • 2
    And the *reason* is that `if (_modeID === undefined)` will throw `ReferenceError` if `_modeID` is an unresolvable symbol (not declared in any containing scope). But `if (typeof _modeID === "undefined")` will not throw even if `_modeID` is unresolvable; instead, the result of `typeof _modeID` is `"undefined"`. – T.J. Crowder Sep 23 '16 at 15:46
  • 1
    Thank you for the explanation @T.J.Crowder – Jeff Jenkins Sep 23 '16 at 15:47
  • This works! Thanks – sab669 Sep 23 '16 at 16:52
  • @T.J.Crowder Thanks for the explanation; that's basically what I was trying to ask in my question but I didn't know the correct words. – sab669 Sep 26 '16 at 13:26