I am having problems understanding when and why I should use the && in an if-statement and when I should put an if statement inside another if statement. I am on the profile lookup challenge (https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup/) and I have these two solutions, where only solution 1 works. To me it look like they should do the same thing. Can anyone please explain to me what the difference is? My brain is having a meltdownâŚ
/Kasama
Solution 1
function lookUpProfile(name, prop ){
for (var i = 0; i < contacts.length; i++){
if (contacts[i]['firstName'] === name) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}
Solution 2
function lookUpProfile(name, prop){
for (var i = 0; i < contacts.length; i++){
if (contacts[i]['firstName'] === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}
return "No such contact";
}
In general, avoid using nested if statements if at all possible because the number of things that can occur in your code multiplies every time you do it. Sometimes itâs necessary, but basic problem is that you normally need to keep all those permutations in your head while youâre writing the code. Its just easier to reason about with less branches, there are fewer failure points. It doesnât really matter here because the program is tiny. Basically a large % of programs you ever write are likely to depend on a set of nested conditional things, thereâs no need to make them more complex than they need to be.
The way I understand it is that using && oparators remove make certain pieces of code easier to read.
letâs say weâve got two variables, a and b, and you only want to do something if they are both zero. You could nest two if statements, but using one and the && operator is shorter, easier to read, and easier to understand.
With just one or two statements it isnât that difficult, but more complex code needs all the help it can get staying readable.
I think I understand how to use them. But what about the code example I provided? Can someone explain to me why the version with the nested conditionals work and the version with the && does not work?
For solution 2, your code always returns when i = 0.
How aboutâŚ
for (var i = 0; i < contacts.length; i++){
if (contacts[i][âfirstNameâ] === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop]; ///return if the name matches and prop exists
} else if (contacts[i][âfirstNameâ] === name{
return âNo such propertyâ; /// return if the name matches but prop doesnât exist
/// It would be better if there was a NAND operator like !&&
} else{
/// Do nothing. Name didnât match.
}
}
/// Exit the loop with no name matches.
return âNo such contactâ;