To interrupt the loop


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) {
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"


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.


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.


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


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.


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


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