1

How do you detect an undefined item in jQuery in an 'if statement' I have tried something like below without any success so far.

 success: function(data){

  if(typeof data.DATA[0].RECIPIENTID = 'undefined'){
     // do nothing                          
   }
   else {
       //else get value
       console.log(data.DATA[0].RECIPIENTID);                       
   }


 console.log(data);

 }
});
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Prometheus
  • 32,405
  • 54
  • 166
  • 302

2 Answers2

9

= is an assigment operator in JavaScript. Use ===, not =.

if(typeof data.DATA[0].RECIPIENTID === 'undefined'){
    // ...
}
// ...

See also Which equals operator (== vs ===) should be used in JavaScript comparisons?

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

undefined does not need quotes ''

    if(RECIPIENTID === undefined){
     // do nothing                          
   alert("undefined");
}
This_is_me
  • 908
  • 9
  • 20
  • 1
    Careful with this one, `undefined` needn't be undefined: `(function(undefined,foo){console.log(foo === undefined); console.log(undefined);})('bar')` paste this in your console – Elias Van Ootegem Aug 28 '12 at 14:48
  • 1
    Compare that to: `(function(foo,undefined){console.log(foo === undefined); console.log(undefined);})(undefined,'bar')` and `(function(foo,undefined){console.log(foo === undefined); console.log(undefined);})()` – Elias Van Ootegem Aug 28 '12 at 14:49
  • I still get TypeError: data.DATA[0] is undefined [Break On This Error] if(data.DATA[0].RECIPIENTID === undefined){ -- any idea why? – Prometheus Aug 28 '12 at 15:03