What's wrong with my code? Basic JS 103

function lookUpProfile(name, prop) {

for (var i=0; i < contacts.length; i++){
  var ct= contacts[i];
if ( ct["firstName"] == name)
{
if (ct.hasOwnProperty(prop))
return ct[prop];
else 
return "No such propery";
}
return "No such contact";

}

}

Hey! can you add a link to the challenge in the post too so its easier for others to help you.

The first thing I did was format your code. You can do that by right clicking in the editor and choosing “Format Document”.
image

Then I added a few console.log in your code for debugging, and called the function with one of the failing tests

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

const output = lookUpProfile("Kristian", "lastName");
console.log({output})

In the console I get this:

{ name: 'Kristian', prop: 'lastName' }
{ i: 0,
  ct: 
   { firstName: 'Akira',
     lastName: 'Laine',
     number: '0543236543',
     likes: [ 'Pizza', 'Coding', 'Brownie Points' ] } }
{ output: 'No such contact' }

That means that the function is not completing the loop, and giving the wrong output. Can you figure out what’s going on?
Hint: When a return statement is executed, the function stops

2 Likes

Thanks! I figured it out…

I did this and it worked:

function lookUpProfile(name, prop) {

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

Is it the cleanest way for writing this function?

check the hints for more solutions, you can compare your function to those