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.

4
  • How are you calling this function? Commented Feb 24, 2014 at 8:59
  • Can you show the code that uses the returned value? Commented Feb 24, 2014 at 8:59
  • I just call it alert(getName(boxid)); Isn't the return statement of the if-condition ending the function? Commented Feb 24, 2014 at 9:00
  • 1
    possible duplicate of How to short circuit Array.forEach like calling break? - especially the SECOND answer: shiny-new-toy disease Commented Feb 24, 2014 at 9:02

3 Answers 3

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;
};
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

it returns the entire boxex-content.
1

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

The function getName only have return null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.