- Home /
Stopping A Loop - Return or Break?
Hello,
I'm using a for loop to cycle through an array of objects to check if a certain attribute exists. I want to be able completely stop the loop if it does find this attribute. I might have multiple objects with these attributes, but I want it to stop after it's found the FIRST one:
for(var i = 0; i < array.length; i++){
if(array[i].attribute == true){
//do something
//stop looking, we've already found what was needed
}
}
I placed a 'return' in the if statement, and it works fine. But I've also tried 'break'. Whats the difference, and which one should I use... If any?
Thanks
Answer by ArkaneX · Oct 14, 2013 at 11:18 AM
break
causes exit from the loop only, so any statements after loop will be executed. On the other hand, return
causes exit from the current function, so no further statements inside this function will be executed.
So - if you want to exit current function after finding the first element, use return
. If you want to continue execution in this function, use break
.
Okay, this loop is in the middle of my Update function, so I want to use break then? As the rest of my code within the update won't get executed... right?
Right - if you want to execute rest of Update
code, you need break
.
Answer by Sparafusile · Oct 14, 2013 at 12:14 PM
Either will work fine in this case. The return statement actually exits the method completely - skipping the execution of the code following the loop. The break statement would just exit the loop and continue executing code after the curly brace of the for statement.
Your answer
Follow this Question
Related Questions
How can I make my for loop "reset" if my array contains an value? 5 Answers
C# List For Loop Only Returns Last Element 0 Answers
Is having a "break" in a "foreach" loop that is itself inside a "for" loop breaking both loops? 3 Answers
crazy loop !!! HELP ME 1 Answer
'brake' statement makes Unity hang ? 0 Answers