'Profile Lookup' Question

I was doing the ‘Profile Lookup’ question and I made my code. However, it doesn’t give me anything so I was wondering what I was doing wrong. Here it is with comments

// Setup
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(name, prop) {
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].hasOwnProperty(name)) { //if the i-th contact has a property of name, and...
            if (contacts[i].prop) { //if that i-th contact has the prop, then...
                return contacts[i].prop // give me the prop at the i-th contact
            } else { // otherwise, give me 'No such contact'
                return 'No such contact'

lookUpProfile("Akira", "likes");

Can you say that no such contact exists inside the loop over all contacts?

1 Like

Could you elaborate? Thank you for the fast reply by the way.

A return statement immediately stops your code as soon as you encounter it. What will happen if the very first contact you check in your loop does not match?

I know that once a return statement is found, the function stops. But I have two questions regarding this:

  1. When I run the code on repl.it, I don’t any response (no undefined, no error message, no ‘No such contact’. If the computer saw the return keyword, wouldn’t it at least put out ‘No such contact’ showing that it reached that last else case?

  2. I thought that since I’m using a for-loop, it would just skip over any object that doesn’t have the property of name.

Oh, you’ve done something stranger than I thought with your code. My mistake!

This literally checks if contacts[i] has a property whose key is given by the name variable. None of these contacts have a property with a key given by Akira or Harry.

Dot notation can only be used with the exact literal property name. You can’t use dot notation with a variable holding the property name.

Why would you put a return statement for "No such contact" inside of a check to see if the name matches? That doesn’t make sense to me.

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