5

I'm trying to process a complete function in an ajax call. If the value is undefined, I want cast a var as an empty string. Otherwise, I would like to capture the value into a string array.

The problem is I'm entering the if statement, even when logging the value of the variable in question returns as undefined. What am I missing here?

completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
        if(typeof $(this).attr("ows_Products") !== undefined) {
          console.log($(this).attr("ows_Products"));
          arr = $(this).attr("ows_Products").split(',');
        }
        else {
          arr = "";
        }
      });
    }
Wesley
  • 5,381
  • 9
  • 42
  • 65
  • 1
    Have a look at this previous question : http://stackoverflow.com/questions/776950/javascript-undefined-undefined – web_bod May 14 '12 at 16:47
  • @web_bod that looked to be more in terms of comparing == to ===, meaning null == undefined = true, whereas null === undefined = false – Wesley May 14 '12 at 16:50

2 Answers2

16

typeof returns a string value, so you'll need to compare with "undefined" as a string. E.g.,

if(typeof $(this).attr("ows_Products") !== "undefined") { ... }

Edit - more info:

If you check out the MDN page for typeof, you'll see this:

The typeof operator returns a string indicating the type of the unevaluated operand.

This is very different from returning the Type itself (which in JavaScript would probably be something like returning a constructor function like String, Array, etc.). Therefore, when using typeof, you'll always be comparing to strings like "object", "string", "undefined", etc.

jmar777
  • 38,796
  • 11
  • 66
  • 64
  • Ahh yes. It's the little things, sometimes. – Wesley May 14 '12 at 16:46
  • 5
    The simplicity of the solution is generally inversely proportionate to how long you spent staring at the problem :) – jmar777 May 14 '12 at 16:49
  • Ha, thanks. I honestly have to give my dad (also a programmer with far more years of experience) credit for that statement. – jmar777 May 14 '12 at 17:18
0
if($(this).attr("own_Products")){
       arr = $(this).attr("ows_Products").split(',');
}else{
       arr=""
}
kannanrbk
  • 6,964
  • 13
  • 53
  • 94