Reputation: 37
The following function in this code is working for a reason I don't understand. Please can someone explain to me why the second if statement wont work without it being nested in the first. Also why doesn't the first statement need a return.
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, prop) {
for (let x = 0; x < contacts.length; x++) {
if (contacts[x].firstName === name) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}
lookUpProfile("Akira", "likes");
Upvotes: 0
Views: 55
Reputation: 99717
I believe your question is fundamentally about nesting if statements and return
, not the specific checks that are being done in each if
statement, so my answer reflects that assumption.
Fundamentally the if statement checks something and when that something is true, it will run some code in brackets.
So when you have 2 nested if statements:
if (a) {
if (b) {
return x();
}
}
In the above example, return x()
will only run if both a
and b
are true.
If we were to re-organize this:
if (a) {
}
if (b) {
return x();
}
In this case, return x()
will if b
is true. a
has no effect.
In this example:
if (a) {
return x();
}
if (b) {
return x();
}
Above, x()
will run if either a
or b
is true. So if b
is true, but a
is false, we will still return.
The intention of your code is to return when both conditions are true. Here's a different way to write this:
if (a && b) {
return x();
}
The reason this is not done, is because the task requires the second condition to return a specific string 'No such property' if the property did not exist, and ignore the contact and move on to the next contact if the property did exist and did not match name
.
Applying that to our if statement, it basically becomes this:
if (a) {
if (b) {
return x();
} else {
return "No such property";
}
} else {
// Do nothing! this else statement doesn't
// exist in your code, but I'm adding it in
// To illustrate that we do nothing if a is
// false
}
There is a more elegant way to write this though, we can inverse the 'b' check and return early:
if (!b) {
return 'No such property';
}
if (a) {
return x();
}
The reason this is correct without nesting, is because:
b
is false, we know for sure that we want to return the error.return
, the function immediately ends/exits, so there's a guarantee that the a
check never happens.Upvotes: 1