Basic Javascript: Profile Lookup (Why is it not working?)

Hi everyone,

I’ve tried looking at the solutions for this exercise, looking at another forum post that was having trouble, and for some reason my code still will not work! I’ve tried comparing it to solutions character for character. I’ve tried logging what my code is returning, and it seems to only return the 0th element’s property and doesn’t appear to increment i, and I don’t know why. But that could be me misunderstanding the issue… Can someone help?

function lookUpProfile(name, prop) 
{
  for (let i = 0; i < contacts.length; i++)
  {
    if (contacts[i].firstName === name)
    {
      if (contacts[i].hasOwnProperty(prop))
      {
        console.log(contacts[i][prop])
        return contacts[i][prop];
      }
      else
      {
        return "No such property";
      }
    }
    else
    {
      return "No such contact";
    }
  }
}

Here’s a screenshot, the formatting in the forum post makes it difficult to follow.

Remember that you can have an if block without an else block attached.

I’ve tried taking the return “No such contact” part out of the else branch and the same thing happened =/

Untitled

Here are the test results.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

It looks like you’re returning before ever checking the second contact in the array.

But my loop is written to iterate through each contact in the array, it just doesn’t seem to be doing that. It doesn’t seem to ever increment i even though the loop is set up to do so… What am I missing?

for (...) {
  if (...) {
    if (...) {
      return
    } else {
      return
    }
  } else {
    return
  }
}

Here’s the code above with all the fluff taken out. It’s impossible to go on to the second iteration in the loop because every single branch has a return statement. Return will immediately exit the function.

Thank you, I finally got it to work. For anyone who has the same problem that might find this thread, I had the “no such contact” return outside of the upper level if-statement, but NOT out of the for loop, which I meant to do but I got curly-brace hypnosis. As colinthornton said, the for loop could never iterate a second time because all branches of the if statements returned out of the function so the loop could never go through every element in the contact list. Thank you, Colin!

1 Like