how to replace undefined with a empty string

texas697 picture texas697 · Sep 16, 2014 · Viewed 26k times · Source

I am using jsPdf. When a field has been left blank "undefined" is printed on the pdf. I would like to replace that with a empty string. I am trying to use a if statement but I am not getting it.

 doc.text(30, 190, "Budget : $");
    if ($scope.currentItem.JobOriginalBudget == "undefined") {

        doc.text(50, 190, " ");
    }
    else {
        var y = '' + $scope.currentItem.JobOriginalBudget;
        doc.text(50, 190, y);
    };

Answer

apsillers picture apsillers · Sep 16, 2014

undefined is a primitive value. Instead of comparing against the identifier undefined, you're comparing against the 9-character string "undefined".

Simply remove the quotes:

if ($scope.currentItem.JobOriginalBudget == undefined)

Or compare against the typeof result, which is a string:

if (typeof $scope.currentItem.JobOriginalBudget == "undefined")