Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge Solution

If/else statement for displaying message for non-student not working correctly

My code works as it should, displaying the student data and breaking the loop. But when I add the else statement, I can only search for the last student (sara) on the list and other searches (bob or alice)produce "No Data Found". Why?

        else{
        studentData= "No Data Found";
        }

https://w.trhou.se/0t053i28or

Oliver Duncan
Oliver Duncan
16,642 Points

It's a little confusing trying to sort through your workspace snapshot. Could you paste the relevant code directly in the browser?

2 Answers

Hi Isabella,

Because you are iterating through the entire students object with a for loop when the code runs, the last item that is iterated over is always going to be "sara". This is why you are getting a "No Data Found" message. Obviously, "sara" will not match "bob", for example. I don't think that this is how you have intended for the code to work.

A simple solution (that is a little bit hacky, in my opinion, but it works), is to add a break statement inside of the if statement after the getReport() function runs, like so:

if (studentIndex.name === search){
   studentData= getReport(studentIndex);
   break;
}

Here, the for loop will stop iterating through the students object if the student's name matches search, so that result will be displayed on the page.

This will give you the desired result. Happy coding!
Leslie

Thanks Leslie, breaking out of the for loop worked. :)

Hi Isabella,

I looked at your code and it could be that in your else statement you are setting the value of studentData to the string " Data not found" . I believe you are trying to print the message using the print function correct?

 if (studentIndex.name===search){
        studentData= getReport(studentIndex);
} else {
print("Data not found"); 
}

let me know if this helps!