To interrupt the loop


#1

var contacts = [bob, mary];

function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
};

function search(lastName) {
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].lastName === lastName) {
printPerson(contacts[i]);
};
};
console.log("Not found!");
};

Hello! Could anybody tell me how to modificate the function search so that it doesn't print out "Not found" after the match? It functions well if there is no such a lastName in the list, but if there is, it prints out both person and "Not found"


#2

That depends whether you want more than one match to be found or not. If not, then just,

return printPerson(contacts[i]);

will take care of that. Then it will only print IF the loop gets to finish.

Otherwise, we need a flag.

var flag = false;
for ( ...  ) {
    if ( ... ) {
        flag = true;
        printPerson( ... );
    }
}
if (!flag) {
    console.log("Not found");
}

Note that there are no semi-colons after any of the curly braces.

Eg.

function foo() {

}
var foo = function () {

};

The latter receives a semi-colon as end-of-statement token for an assignment statement. The former is a declaration and the interpreter knows it by its object type on the first pass at run time. The second is not scanned until the second pass, so the semi-colon tells the interpreter where to continue during the first pass. (Read up on hoisting for more information.)

if () {

}
for () {

}
switch () {

}
while () {

}

All of the above are declarative so need no end-of-statement token.

do {

} while ();

is not declarative so does need one.


#3

Oh, thank you very much!! But I'm shocked: the problem seemed so easy, but it turned out difficult to code!!


#4

easy is relative. Visualizing is not always easy even if we are pretty sure what outcome to expect. There is no penalty for trial and error while we play out our theories and hypotheses. Control flow is a straight forward but often complicated thing to think through. Give yourself a chance and time to think things over, and don't be afraid to ask. No question is dumb if the person asking it really wants an answer.


#5

I'm not an English native speaker, but hope you understand me: I'm VERY grateful for your kindness, your fast help and support!


#6

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