Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble with undefined !== undefined

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 = "";
        }
      });
    }
like image 366
Wesley Avatar asked May 14 '12 16:05

Wesley


1 Answers

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.

like image 77
jmar777 Avatar answered Oct 11 '22 23:10

jmar777