Nested if vs &&?

Nested if vs &&?
0

#1

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 }


#2

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 }


#3

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 :slight_smile:


#4

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


#5

Thanks. I’ll study that a bit! Not sure if it’s related but even if I use only one ‘&’ it doesn’t work…


#6

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.