Hi all.
I’m working on the Profile Lookup challenge and the only difference between my code and wiki’s example is that I’m using && instead of nested if statements. If I rewrite my code using if statements it passes.
Why using the && in this case doesn’t work?
function lookUpProfile(firstName, prop){ // Only change code below this line for (var x=0; x < contacts.length; x++) { if (contacts[x].firstName === firstName && contacts[x].hasOwnProperty(prop)){ return contacts[x][prop]; } else { return "No such property"; } } return "No such contact"; // Only change code above this line }
Ok, I was able to make it work by adding an else if statement where the ‘else’ was:
function lookUpProfile(firstName, prop){ // Only change code below this line for (var x=0; x < contacts.length; x++) { if (contacts[x].firstName === firstName & contacts[x].hasOwnProperty(prop)) { return contacts[x][prop]; } else if (contacts[x].hasOwnProperty(prop) === false) { return "No such property"; } } return "No such contact"; // Only change code above this line }
Can someone please explain in simple terms the differences between both if statements and why I had to add the “else if (contacts[x].hasOwnProperty(prop) === false)” part when using &&?
Thanks
Well are you familiar with truth tables?
You will need two truth for it to return contacts[x][prop]
otherwise if any of the two are false then it would fail.
See http://forum.freecodecamp.com/t/javascript-truth-table/15974
Thanks. I’ll study that a bit! Not sure if it’s related but even if I use only one ‘&’ it doesn’t work…
Well I think you have to use two. I honestly didn’t go deep into the algorithm to find the problem but I feel it could be on that which is why I pointed that out.