Suppose I have an array names = '[joe', 'sam', 'tim'];
and I want to search for a name and if it is found to return true.
My instinct is to write:
function(names, name){
for (var i = 0 ; i<names.length; i++){
if (names[i] == name) return true;
else if (names[i] != name) return false;
}
}
The problem is that this will only search the first item in the array and will break out of the loop whether it is true or false. How can I search the entire array before returning anything?
like it was pointed out return will quit the current function with the result attached to it., which would stop any following code inside the function to run(including remaining for loop iterations). In order to run the entire for loop thru the array, you shouldnt let it return the function(unless the loop already answered its purpose, which in this case is the question, does the array contain a name).
There are several approaches to make your code fulfil its purpose. If you need assistance to figure them out, let us know
After the for loop is completely done iterating, but in that case the return statement would seem to go outside of the loop to let it finish iterating but that defeats the whole purpose of the loop.