Sean Bannister
Sean Bannister

Reputation: 3185

Javascript: Best way to check value of variable which might be undefined

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?

Upvotes: 0

Views: 475

Answers (2)

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

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.

Upvotes: 1

zellio
zellio

Reputation: 32484

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

Upvotes: 0

Related Questions