Need help figuring out something


#1

Before anything else, first of all, hello everyone!
I need your help in understanding a line of code, it starts like this:

/* array students at the bottom holds 3 objects and their keys–I know you all know this just by looking at the code(for me it would take a bit of time to translate it XD) but it doesn’t hurt to tell you the thought process.*/

function createStudent(name1, name2) {
return object = {
firstName: name1,
lastName: name2
};
}

var tim = createStudent(“Tim”, “Garcia”);
var elie = createStudent(“Elie”, “Schoppik”);
var david = createStudent(“david”, “game”);

var students = [tim, elie, david];

// at the bottom I would like the function to return true, which it does–question is after the code at the bottom

function findStudentByFirstName(name) {
for (var i = 0; i < students.length; i++) {
if (students[i].firstName.toLowerCase() === name.toLowerCase()) {
return true;
}
}
return false;
}

findStudentByFirstName(“david”);

/* now for the question: the code at the bottom was the one I coded first–since I’m more accustomed to using the “else” scenario it’s the one I used–but the value kept turning false. Can you show me and explain to me why? Wouldn’t the “else” scenario work too? It seems I’m doing it wrong but I can’t figure out where or why. I appreciate any help that you can give me. Thank you. */

function findStudentByFirstName(name) {
for (var i = 0; i < students.length; i++) {
if (students[i].firstName.toLowerCase() === name.toLowerCase()) {
return true;
}
else {
return false;
}
}

}

findStudentByFirstName(“david”);


#2

Hello, I will try to explain as best as I can, this was your code:

function findStudentByFirstName(name) {
    for (var i = 0; i < students.length; i++) {
        if (students[i].firstName.toLowerCase() === name.toLowerCase()) {
            return true;
        }
        else {
            return false;
        }
   }
}

lets follow the code and see what caused the unexpected behaviour:

findStudentByFirstName("david");

1° run of the for loop:

students[i].firstName.toLowerCase() === "tim"
name.toLowerCase() === "david"

so the check is false and the code follows the else statement returning false.

The problem is that the for never goes beyond the first loop and the function will always return false, unless you call:

findStudentByFirstName("tim");

The other code you used, without the else statement let the for loop to search the entire array.


#3

Thanks for putting in the correct format GianBe, looks much better, will do that in the future–much better to read.

I think I got your explanation. I appreciate it, thanks.