0

I need to check if thevar[2] === 'debug' however thevar[2] might be undefined so if I ran the following code with it being undefined javascript would throw an error:

if (thevar[2] === 'debug') {
  console.log('yes');
}

So what I'm currently doing is:

  if (typeof thevar[2] !== 'undefined') {
    if (thevar[2] === 'debug') {
      console.log('yes');
    }
  }

Is this really the best way to do this?

Sean Bannister
  • 3,105
  • 4
  • 31
  • 43
  • 1
    dupe: http://stackoverflow.com/a/416327 – Ahmet Kakıcı Feb 16 '12 at 07:37
  • Do you mean that thevar is undefined and not thevar[2]? – Laurent Feb 16 '12 at 07:38
  • @AhmetKakıcı that's kind of a bad example, it looks like the question got changed to the same question as this, but the accepted answer is not appropriate for the question. In fact the mistake being made in this question could easily result from seeing that question and excepted answer. – Dagg Nabbit Feb 16 '12 at 07:46

2 Answers2

1

Your first example will not throw an error. Undefined properties of objects evaluate to undefined, but they don't throw errors.

var foo = {};
var nothing = foo.bar; // foo.bar is undefined, so "nothing" is undefined.
// no errors.

foo = [];
nothing = foo[42]; // undefined again
// still no errors

So, your second example is not needed. The first is sufficient.

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
0

If you can run if (typeof thevar[2] !== 'undefined') ... then you can reference thevar and you can run anything else with it.

If your array exists then checking against a value works fine, even if that value is undefined.

> var x = [];
    undefined
> if ( x[0] === "debug" ) console.log("yes");
    undefined
> if ( x[100] === "debug" ) console.log("yes");
    undefined

The issue arises only when the array doesn't already exist. So as long as you know thevar has value then no check needed. Otherwise just check if thevar has value or do a little var assignment trick like

var thevar = thevar || [];
//work with thevar with impunity
zellio
  • 31,308
  • 1
  • 42
  • 61