6

My question is about preventing an "variable is undefined" error more effiencitly.

e.g

If I use the following code:

if (array[index] != undefined)
{
  if (array[index].id == 1)
  {
    // code 
  }
}

It will work fine. But, am I able to use

if (array[index] != undefined && array[index].id == 1)
{
 // code
}

without getting an "variable is undefined" error, if array is undefined?

(I can't exactly test this in my code right now because I'm building a client-server application, and I'd have to alter many lines to try it, so I'm asking it here. I'm sorry if it's not appropriate)

  • 1
    Most (all?) browsers have a console that you can use to run javascript and test it on a page (just press F12 and click console). You can also use http://CodePen.io or http://JSFiddle.net if you need to test ideas. For this case you can just define a new variable, run it, and see what happens. For example... `var tmp = []; if(tmp[0] != undefined && tmp[0].id == 1) { alert("In if!") } else { alert("Skipping block.") }` – Marie Mar 28 '16 at 12:47

6 Answers6

5

&& will return true only if both the values of (a && b) a and b are truthy values.

If first operand(expression) is evaluated as false, second operand(expression) is not evaluated at all because the result would always be false

Rayon
  • 36,219
  • 4
  • 49
  • 76
  • 3
    For more information you can read the [MDN on Javascripts Logical Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators). Specifically the section titled `Short-Circuit Evaluation` – Marie Mar 30 '16 at 12:36
2

is better practice to use typeof to evaluate undefined variables:

if ( typeof array[index] !== 'undefined' && array[index].id == 1)
{
   // code
}

Remember to check the string 'undefined' not the primitive value.

More info in MDN

ismapro
  • 162
  • 9
1

No, if array is undefined, you will need an if statement that looks something like this:

if (array && array[index] !== undefined && array[index].id === 1) {
   // do things
}

The first condition that if false will stop the evaluations of all the other conditions. The only way this will fail is if you are running you code in strict mode and have never declared var array

JoshWillik
  • 2,624
  • 21
  • 38
1

The if will return true only if all the conditions inside the paranthesis of if are true.

If any one of the expression is evaluated as false, The whole expression is evaluated as false.

1

If you have to check array itself is undefined then you will have to check typeof array also there. Something like this:

if(typeof array !== 'undefined'){
    if ( typeof array[index] !== 'undefined' && array[index].id == 1)
    {
       // code
    }
}
Luke P. Issac
  • 1,471
  • 15
  • 32
0

Yes, if the first condition fails, it will short-circuit and ignore the other conditions, like in any language.

George Kagan
  • 5,913
  • 8
  • 46
  • 50