How not to loop an array

I realised that the first line of this function will always make it always return “No such contact” if the name passed isn’t the first array item. I have a surface understanding of this. Can someone please explain further?

Do you understand why it does this?

Not really, Kindly explain it to me

Think of what return is actually doing in your for loop.

When a return statement is executed, the function immediately exits and returns the value back to the call function. This means you only want to return the “No such contact” string when you know for sure you have checked all of the first names against firstName. If you think about the place in the code when you would know for certain that all names have been checked, that is the place you want to put this return statement.

Thanks for explaining. Is there any other way to do this without moving that block of code outside the for-loop?

No. It is kind of like me giving you a list of names on a piece of paper and asking you to tell me if a specific name is on the list, but then tell you not to actually look at the list. You have to be able to go through the entire list before you know if the name is there or not.

EDIT: Technically, you could approach the problem differently, where you create a variable (let’s call it result) and initialize it as “No such contact”. Next, you would keep your other two if statements in place but instead of returning a value inside the if statement blocks, you would assign the applicable value to your result value and then “break” out of the for loop. Then after the for loop, you would just return the result variable. If the break statements never stop the for loop prematurely, then the “No such contact” value would be returned as it never was changed inside the for loop.

Wow, it’s super clear now… Thanks @RandellDawson. it’s 3:26am here, I can now go to bed

1 Like