Simple if statement not working!


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) {
    for (let i = 0; i < contacts.length; i++) {
        if ((name === contacts[i]["firstName"])) {
            return contacts[i].firstName;
        } else return "No such name"
    }
}

// Change these values to test your function
console.log(lookUpProfile("Kristian"));
function lookUpProfile(name) {
    for (var i = 0; i < contacts.length; i++) {   
        if ((name === contacts[i]["firstName"])) {
          	console.log("running if");
            return console.log(contacts[i].firstName);
        }else{ console.log("no such a name in",contacts[i].firstName );}
    }
}

// Change these values to test your function
lookUpProfile("aa")

Oh, the “return” will end the for loop, so I was trying to don’t use the return. but I fix it in a bad way. I’m thinking a better way to imporve it

2 Likes

You should provide more context such as what’s the problem link and the goal of the problem. As far as I can see here, if the variable name matches the contacts[i][“firstName”], it returns the contacts[i].firstName value, which is the same as the variable name. Sounds kinda redundant. Probably it should return true?

Notes:

  • You don’t need to use double parenthesis on conditional functions (()).
  • Also don’t forget to add ; at the end of each command. That else has an inline return without one. It’s not mandatory but it’s better for consistency.
1 Like