0

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.

marcel
  • 3,231
  • 8
  • 43
  • 76
  • How are you calling this function? – RononDex Feb 24 '14 at 08:59
  • Can you show the code that uses the returned value? – Raul Rene Feb 24 '14 at 08:59
  • I just call it alert(getName(boxid)); Isn't the return statement of the if-condition ending the function? – marcel Feb 24 '14 at 09:00
  • 1
    possible duplicate of [How to short circuit Array.forEach like calling break?](http://stackoverflow.com/questions/2641347/how-to-short-circuit-array-foreach-like-calling-break) - especially the SECOND answer: _shiny-new-toy disease_ – mplungjan Feb 24 '14 at 09:02

3 Answers3

5

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;
};
kaspermoerch
  • 16,127
  • 4
  • 44
  • 67
1

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.
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

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

The function getName only have return null;

francadaval
  • 2,451
  • 3
  • 26
  • 36