user2565289
user2565289

Reputation:

if else variable scope shows undefined in else in js

I am defining a variable named htmlARR in an if/else block. If I comment out the variable in the else block, it shows undefined, but if I don't comment it out, it shows the result.

NOTE: I can't the scope of variable come inside else also.

coffeeAllColGenHTML : function (allData, more) {
            console.log("WATER" + allData.WATER);
            console.log("providerWATER" + allData.PROVIDER_WATER);

            if (more) {
                var htmlArr = [];
                htmlArr.push(allData.COFFEE_DISH, "<br/><span class='sub-detail'>", allData.WATER, "</span>");
                return htmlArr.join("");
            } else {
/* this line */ //var htmlArr = [];
                htmlArr.push(allData.COFFEE_DISH, "<br/><span class='sub-detail'>", allData.PROVIDER_WATER, "</span>");
                return htmlArr.join("");
                //return allData.COFFEE_DISH;
                //console.log(allData.COFFEE_DISH);
            }
        },

Upvotes: 0

Views: 285

Answers (1)

Michael Benin
Michael Benin

Reputation: 4332

You need to scope your variable declaration:

coffeeAllColGenHTM: function (allData, more) {
        console.log("WATER" + allData.WATER);
        console.log("providerWATER" + allData.PROVIDER_WATER);
        var htmlArr = [];

        if (more) {
            htmlArr.push(allData.COFFEE_DISH, "<br/><span class='sub-detail'>", allData.WATER, "</span>");
            return htmlArr.join("");
        } else {
            htmlArr.push(allData.COFFEE_DISH, "<br/><span class='sub-detail'>", allData.PROVIDER_WATER, "</span>");
            return htmlArr.join("");
            //return allData.COFFEE_DISH;
            //console.log(allData.COFFEE_DISH);
        }
    },

Upvotes: 9

Related Questions