-1

I have a program like this

var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];


function lookUpProfile (firstName, prop) {
    // Only change code below this line

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

// Change these values to test your function
lookUpProfile("Harry", "likes");

The problem is that if I do not use else condition, the above code works with no problem. But when I add else condition, the first condition does not execute.

var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];


function lookUpProfile (firstName, prop) {
    // Only change code below this line

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

// Change these values to test your function
lookUpProfile("Harry", "likes");

When I execute this code with else condition, the first condition does not execute and jumps directly to the else condition. What step am I missing or doing wrong please?

1
  • What happen if multiple users with the same firstName? Commented Nov 2, 2016 at 14:13

4 Answers 4

4

Move the else part to the end of the function, because a single return like in the for loop, ends the function immediately.

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

var contacts = [{ firstName: "Akira", lastName: "Laine", number: "0543236543", likes: ["Pizza", "Coding", "Brownie Points"] }, { firstName: "Harry", lastName: "Potter", number: "0994372684", likes: ["Hogwarts", "Magic", "Hagrid"] }, { firstName: "Sherlock", lastName: "Holmes", number: "0487345643", likes: ["Intriguing Cases", "Violin"] }, { firstName: "Kristian", lastName: "Vos", number: "unknown", likes: ["Javascript", "Gaming", "Foxes"] }];

console.log(lookUpProfile("Houdini", "likes"));
console.log(lookUpProfile("Harry", "likes"));
console.log(lookUpProfile("Harry", "friends"));

A short way would be the use in ES6 of Array#find

Sign up to request clarification or add additional context in comments.

6 Comments

the problem is not with "No such property", Problem is with the condition which tells there is no such content. else if(contacts[i].firstName!==firstName) { return "No such contact"; }
As an explanation, it should be noted that when you return something, it marks the end of the function and no further steps/loops will be processed.
These solution is not handling multiple Objects in contacts array with the same firstName.. Check my answer
@YosvelQuintero, i think, it's not ment for multiple occurence of the same first name.
firstNames was and will be never unique.. I think developers should make improvements if possible ;)
|
1

return statement stops execution of the loop and exits the current function. return always exits its function immediately, without proceeding the further execution if it's inside a loop.

Alternatively, I suggest the @Nina Scholz answer.

Comments

1

The following function should work ok:

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

In the original function I see three problems:

1) Problem in the for -loop condition

The original for-loop was the following

for(var i=0; i<=contacts.length; i++)

In the loop the stop condition was i <= contacts.length. The contacts array is having zero -based indexing, thus the original condition was: i is "less than equal" as contacts.length. The problem is that the length of contacts is 4, but as the indexing is zero -based, you will get an error when i incrments to 4 and thus goes over the array's boundaries. Therefore the condition must be i is "less than" contacts.length.

Fix: for(var i=0; i<contacts.length; i++)

2) Extra "=" in the if -clause:

if(contacts[i].firstName===firstName)

Fix:

if(contacts[i].firstName==firstName)

3) Else if -condition triggers always if firstName is not the 1st index

The else if -condition triggers always if the first contact is not the one that we're looking for, i.e. if if(contacts[i].firstName==firstName) fails, then else if will be true.

Fix: Move the 'return "No such contact";' to the end of the function. As we return value from the other branches already, it's more convenient to return "No such contact" in the end if we didn't get a match.

Hopefully this helps a bit. I'm happy to help more if you have further questions.

Thanks!

Comments

0

What is happening is practically you enter your loop, check the first contact to see if is the contact you're looking for, and if isn't, before you have a chance to check the other contacts, you see the return "No such contact"; line and exit function.

As in @Nina Scholz's answer, you can carry the return to the end, because you know that if you reach that point, you have looked through all contacts and haven't returned from the function.

I don't have enough reputation to comment - and as this is an answer, I present achieving this with minimum edits on your code:

function lookUpProfile (firstName, prop) {
    // Only change code below this line

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

    //At this point you know for sure that you haven't 
    //found the contact you're looking for.
    return "No such contact";
}

5 Comments

you need to eliminate the else part.
The first else? Why? To me it means I have found the correct person, but they don't have the property I'm looking for. For example, lookUpProfile("Harry", "dislikes");
but you return to early, because you could have later some find.
But if I found the contact with that name, and they don't have the property I'm looking for, why would I keep looking? Of course I'm assuming that contacts have unique names, otherwise it would make no sense to search for a specific person. (If there are two Harry's, whose likes am I going to return? Makes no sense.)
If the name & surname combination was unique instead, you could edit the function parameters and the if condition to reflect that - and you would still be able to use the else condition, because once you've found the right person, you've found the right person.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.