0

I'm sure this is a noob issue but I'm a little confused. My understanding is that when a return statement is reached it should stop the function, however in the example below it doesn't seem to. Would someone please explain what's going on?

Fiddle

var hasTerm = function(obj,term){

    $.each(jsonObject,function(key, value){
        if (value == term){
            console.log("conditional");
            return true;  
            console.log("conditional after return");
        };

        if(typeof value == (Object || array)){
        hasTerm(value,term);
        }
});
    return false;
}
ozil
  • 6,930
  • 9
  • 33
  • 56
Ben Pearce
  • 6,884
  • 18
  • 70
  • 127
  • What makes you think `return` doesn't exit the function? What behavior are you seeing? – David Feb 22 '15 at 23:16
  • 3
    note that there is more than one function shown... you might want to use [].some/[].every if you want to bail early on the iteration... – dandavis Feb 22 '15 at 23:17
  • If you look at fiddle the function moves on to parse "key2" and returns false. – Ben Pearce Feb 22 '15 at 23:18
  • 2
    i dont see the text "conditional after return" in the fiddle's console, so it seems to be working for me. – dandavis Feb 22 '15 at 23:19
  • `return` only exits the function in which it's called. It doesn't exit *all* functions in the stack. `each()` will continue to loop through the array as expected in this case. – David Feb 22 '15 at 23:22
  • Btw, `typeof value == (Object || array)` will never be true. You seem to want `typeof value == "object"` – Bergi Feb 22 '15 at 23:24
  • How do I stop the parent function and do a return from a child function? – Ben Pearce Feb 22 '15 at 23:24

1 Answers1

0

The $.each is looping through all of the object collections passed in "jsonObject". Likely it is stopping on an object and then restarting on the next object. Does the console window ever show "conditional after return"?

Use "return false" to stop the iteration.

  • It does not show "conditional after return". Are you saying that the return function is shutting down to $.each function and not the parent? If that's the case what's the work around? – Ben Pearce Feb 22 '15 at 23:21