Basic JS: Profile Lookup
Ok. I know, how to do this challenge with “for” loop, but I want do it with “while” loop.
I almost done, except this instruction (“Bob”, “number” should return “No such contact”).
The code with “for”:
for (var i = 0; i < contacts.length; i++){
if (contacts[i].firstName === firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
My code with “while”:
var i = 0;
while (i <= contacts.length) {
if (contacts[i].firstName === firstName)) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}
i++;
}
So, my question is: how to carry out this instruction “Bob”, “number” should return “No such contact”?
I think the condition in the while-loop should be a <
, not a <=
. You also don’t have a return 'No such contact';
after your while-loop.
“<” or “<=” - work both.
return “No such contact” after while-loop - not working.
I just tried it with a while loop. I used <
and added return 'No such contact';
after the loop and it passed.
You should be able to replace a for-loop with a while loop like this:
for (var i = 0; i < contacts.length; i++) {
// loop body
}
does the same thing as
var i = 0;
while (i < contacts.length) {
// loop body
i++;
}
Also, this might sound silly, but you have an extra )
in the line with the if
.
1 Like
Great thank’s, kevcomedia!
I dont know, why this is didn’t work befor, but right now it is!
I think, that I put the “return” in the wrong place.
Yep, the problem was in “<” vs “<=”.
Thank’s a lot!
Hello,
I face the same issue. What i wrote is
for (i=0; i<contacts.length; i++) {
if (contacts[i][“firstName”]==firstName && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
}
}
for (i=0; i<contacts.length; i++) {
if (contacts[i][“firstName”]!=firstName) {
return “No such contact”;
}
}
for (i=0; i<contacts.length; i++) {
if (contacts[i].hasOwnProperty(prop)) {
return 0;
} else {
return “No such property”;
}
}
However, the last issue, no such a property, is not correct:
“Akira”, “address” should return “No such property”
What’s wrong in the logic of the code?
for (var i = 0; i < contacts.length; i++){
if (contacts[i].firstName === firstName) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
Read this code and try to understand it.
2 Likes
I thought something similar but your code is beter.
Thank you for your response.