There are three things:
Firstly, it is better to use the strict equality operator === in your comparisons.
Secondly, move your last return statement return "No such contact" outside of the for loop.
Thirdly, your return statement return contacts[i][prop] should be accessed using the array notation as in some cases an array is returned.
There are three return options: return the property, return No such property, or return No such contact. Currently, you are handling all three of those on the first record. By having the No such contact inside the loop, as @sabahat70 says, you’re breaking the for loop entirely.
And, as was pointed out, there are two different ways of accessing properties:
if you are accessing them directly, you can use ‘dot notation’: collection[i].lastName is perfectly fine, as lastName is an actual property on the object.
if you are accessing them by a variable (like prop, which is a string passed as a parameter), you need to use ‘bracket notation’: collection[i][prop] will see this as collection[0]["lastName"], and will work properly for what you’re doing.
It’s worth expanding on why the return statement goes outside of the for statement.
When it does its first for loop and sees the else statement, it returns data to the function, ending the loop. You need it to loop through all of the data first and if it can’t find it, then you return the fallback text.
It worked, thank you for your help. I’m still however a lil lost on why it should be outside the loop, I mean it is inside it, but under a condition, why the “for” loop keeps going on to the “else” statement if one of the two first conditions is fufilled, and therefore overriding the previous “return”? If I understood correctly, a function stops executing commands once it reaches a “return” statement, and the “if” conditioning doesn’t need a “break;” like the “switch”. Thank you.
there is no overriding a return statement, if it is reached, it is executed, the value is returned from the function and the function stops
function is searching for contact “Sherlock” (name is "Sherlock")
first iteration of the loop, i is 0, firstName is "Akira"
if statement, condition is false, it is not executed
else if statement, condition is false, it is not executed
else statement, executed as everything else is false, return statement executed, the function STOPS, as such it is impossible to meet other return statements in following iterations of the loop