marcel
marcel

Reputation: 3272

javascript function ignores return statement

I have a function returning null by default, and another value by condition.

var getName = function(boxid){
    var boxes = localStorage.getItem("boxes");
    if((boxes != "" )&& (typeof boxes != "undefined") &&( boxes != null))
    {
        boxes = JSON.parse(boxes);
        boxes.forEach(function(box){
            if(box.id == boxid)
            {
                console.log("box.name: "+ box.name+ " boxid: "+ box.id+ " : "+ boxid);
                return box.name;
            }
        });
    }
    return null;
};

the correct array-entry gets found. but the return statemant doesn't return it, it's ignored.

Upvotes: 0

Views: 898

Answers (3)

kaspermoerch
kaspermoerch

Reputation: 16570

The reason your return statement isn't working is because it is local to the forEach's callback, and not related to your getName-function.

You should use a normal for-loop instead:

var getName = function(boxid){
    var boxes = localStorage.getItem("boxes");
    if((boxes != "" )&& (typeof boxes != "undefined") &&( boxes != null))
    {
        boxes = JSON.parse(boxes);
        for(var i = 0; i < boxes.length; i++) {
            if(boxes[i].id == boxid)
            {
                console.log("boxName: "+ boxes[i].name+ " boxID: "+ boxes[i].id+ " : "+ boxid);
                return boxes[i].name;
            }
        };
    }
    return null;
};

Upvotes: 5

francadaval
francadaval

Reputation: 2481

The return box.name; is for the function inside forEach.

The function getName only have return null;

Upvotes: 1

xdazz
xdazz

Reputation: 160973

Because they are in different scope.

You could use filter and map function:

boxes = JSON.parse(boxes);

// the result will be an array of box name
return boxes.filter(function(box){
    return box.id = boxid;
}).map(function(box) {
    return box.name;
});

// if the box id is unqic, then just get the first one.

Upvotes: 1

Related Questions