Dora Dora - 2 months ago 8
Javascript Question

my variable is returning empty why?

I am not sure if this is a scope problem because all seems reasonable to me but somehow my variable keeps on returning empty.

I am trying to refactor these two similar codes and put into function.
the codes works perfectly to my needs but when I try to refactor, the variable keeps on returning empty.

Can someone please give me a hand?

This is the two similar codes I have which works fine

var productOutOfStock = "";
$(".availability.outofstock").each(function(){
var outOfStockMsg = $(this).text();
var name = $(this).closest(".basket-items").find(".product-name").text();
if(outOfStockMsg != ""){
productOutOfStock += name + "<br>";
}
});

var productOffline = "";
$(".availability.instock").each(function(){
var outOfStockMsg = $(this).text();
var name = $(this).closest(".basket-items").find(".product-name").text();
if(outOfStockMsg != ""){
productOffline += name + "<br>";
}
});


This is the refactor I am trying and giving me empty string

var productOutOfStock = "";
var productOffline = "";

function getProductNames(offOrNostock, nameList){
offOrNostock.each(function(){
var message = $(this).text();
var productName = $(this).closest(".basket-items").find(".product-name").text();
if(message != ""){
nameList += productName + "<br>";
}
});
console.log(nameList); //this does show the names
}

getProductNames($(".availability.outofstock"), productOutOfStock);
getProductNames($(".availability.instock"), productOffline);
console.log(productOutOfStock); //this is giving me empty string


Thanks in advance for any help.

Answer

JavaScript is a pass-by-value language, so your strings are passed as copies. When the function modifies the nameList variable, it's modifying a copy of the string you pass as the second parameter.

You could modify your function so that it returns the updated string:

function getProductNames(offOrNostock, nameList){
    offOrNostock.each(function(){
        var message = $(this).text();
        var productName = $(this).closest(".basket-items").find(".product-name").text();
        if(message != ""){
            nameList += productName + "<br>";
        }
    });
    return nameList;
}

productOutOfStock = getProductNames($(".availability.outofstock"), productOutOfStock);
Comments