0

I have this jQuery code part:

$.each(myArray, function(index, val) {
        
  if (val == "Test" ) {
     
     console.log("FOUND")
     return
  
  }
    
});
    
console.log("DEBUG")

I get both logs: "FOUND" and "DEBUG"

But I would like to exit the function directly after the value was found. I guess that my "return" only exit the loop, but not the whole function.

Is there any solution that I can exit the loop and exit the function in one line?

Trombone0904
  • 4,132
  • 8
  • 51
  • 104
  • `return` ends the anonymous function you pass as callback to `$.each()`. It doesn't end `$.each()` – VLAZ Mar 02 '22 at 06:23
  • `return` always used to get out from the current scope function execution and this is how it is working in your code. – Debug Diva Mar 02 '22 at 06:23
  • 5
    "*Is there any solution that I can exit the loop and exit the function in one line?*" why even use jQuery for this? Use a regular loop or a JS iteration method like `.find()` or `.contains()` – VLAZ Mar 02 '22 at 06:24
  • https://stackoverflow.com/questions/1799284/how-to-break-exit-from-a-each-function-in-jquery – Brad Huang Mar 02 '22 at 06:26

0 Answers0