Still confused on how to search the entire array before returning

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?

The return keyword forces your function to stop. If you don’t want the function to stop, then you have to move the return keyword.

2 Likes

You can make this work with a good ol’ for loop but there is also a built in array method for this kind of situation.

If you google, "how to check if item exists in array javascript’
then the first result is for the array method I am talking about :grinning:

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

Yes I am aware of this. I thought for this type of problem you had to put return somewhere in the function at least once.

You do have to put the return statement somewhere, but it shouldn’t be in a place that forces the loop to stop early with the wrong result :slight_smile:

When can you say that no name matches?

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.

Why would it defeat the purpose of the loop?

If you find a match, you should return true.

If you don’t find a match, you should return false.

Oh yeah I guess you’re right.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.