Search code examples
javascriptloopsreturnbreak

Javascript function doesn't break on return?


I know you are supposed to be able to break out of an each statement by returning, which is what I'm trying to do, but I must be doing something wrong and it seems so simple I can't find it.

I have code like this

function create() {
  var test = hasThing();
  if (test) {
    $('#myForm').submit();
  } else {
    alert('you suck!')
  }
}

function hasThing() {
  $('.selects').each(function() {
    if (this.value != "") {
      return true;
    }
  });
  return false;
}

I have set breakpoints on "return true;" and hit it but var test is always false because for some reason the .each() loop continues and the hasThing() function continues. I've tried switching things around so that I return false in the .each() just in case for some reason that mattered but it didn't change anything.

I don't get it. Seems counter to how the documentation says it should work.


Solution

  • Your return true; statement returns from the anonymous function given to each. The return false; line is always executed which explains why var test is always false.

    Change your code to

    function hasThing() {
      var hasThing = false;
      $('.selects').each(function() {
        if (this.value != "") {
          hasThing = true;
          return false; // breaks the $.each, but does not return from hasThing()
        }
      });
      return hasThing;
    }