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

Pimwipha Cheaptumrong
Pimwipha Cheaptumrong
10,977 Points

Why we create a new function for the student report message and why we move the for..loop inside while..loop?

Hi, I am watching the challenge video. I have so many questions in my head right now. I still wonder why we need to create a new function for student reports outside and how do I know that it's time to create function. Why we just don't create a function inside for for..loop itself? Why we also move the for..loop inside while..loop? Personally I am still not very clear about while..loop and for..loop 100%. It's getting confused how we put all of these things together. Thank you so much. I have watched the videos multiple times and I still don't understand it for a while now.

Steven Parker
Steven Parker
229,982 Points

It would help to see the code you are referring to, can you provide a link to the course page, and an approximate time index into the video?

2 Answers

Pimwipha Cheaptumrong
Pimwipha Cheaptumrong
10,977 Points

Oh, I am so sorry. Here is the link to the lesson.

https://teamtreehouse.com/library/the-student-record-search-challenge-solution

The Student Record Search Challenge Solution (7:26) with Dave McFarland

//code below

var message = ''; var student; var search;

function print(message) { var outputDiv = document.getElementById('output'); outputDiv.innerHTML = message; }

function getStudentReport( student ) { var report = '<h2>Student: ' + student.name + '</h2>'; report += '<p>Track: ' + student.track + '</p>'; report += '<p>Points: ' + student.points + '</p>'; report += '<p>Achievements: ' + student.achievements + '</p>'; return report; }

while (true) { search = prompt('Search student records: type a name [Jody] (or type "quit" to end)'); if (search === null || search.toLowerCase() === 'quit') { break; } for (var i = 0; i < students.length; i += 1) { student = students[i]; if ( student.name === search ) { message = getStudentReport( student ); print(message); } } }

Steven Parker
Steven Parker
229,982 Points

The inner loop checks every student in the list to see if there is a match for the name you typed in.

The outer loop lets you repeat the entire process to keep checking more names.