I know people have asked this question several times but I need some help identifying why my function doesn’t work and if I am just misunderstanding how if statements work.
function lookUpProfile(name, prop){
var doesItExist;
for (let user of contacts) {
if (user["firstName"] === name) {
doesItExist = user.prop
} if (user[name] !== name) {
doesItExist = "No such contact";
} if (user.hasOwnProperty(prop) === false) {
doesItExist = "No such property";
}
} return doesItExist;
}
From what I can imagine you want to look up a name and a property.
If the name isn’t there, return no such contact
If the name is there, but not the property, return no such property
If the name is there, and the property, return the property.
If you agree, try to re-write what you have.
Right now, it’s not doing that.
This is just how I think of it, probably not completely correct. But it may help…
function lookUpProfile(name, prop){
// Input: name, prop: strings
// return prop, or no such prop, or no such name.
for (let user of contacts) {
//loop over array of contacts
if (user["firstName"] === name) {
//if name is there
if(user[prop]) return user[prop] //if prop is
else return `${prop} doesn't exist` //if isn't
}
else return `${name} doesn't exist`; //if name is not there
}
I agree with the answers you’ve gotten already. I just wanted to note, shen you’re trying to figure out why your code isn’t working, it really helps to take a concrete example. So:
If you look at what your code is actually doing, let’s say you try to look up “Harry”. The loop will find Harry, and it will do something with doesItExist, BUT right after that it will find Sherlock, so doesItExist will get changed back to “No such contact”.
This problem suggests that, like @Minsky suggested, you need to use a “return” as soon as you find the user, not at the end of the whole loop.
I guess I was trying to compare whether the name argument passed into the function was the same as the name property in the object. And I don’t really understand how the if statements work then. You are saying they all run at the same time?
is Harry ever a property key? (remember that properties have the key: value format)
has a property ever have the same key and the same value?
that’s the issue