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

Anik Devaughn
Anik Devaughn
7,751 Points

Really need you help with this challenge: "The Student Record Search Challenge Solution"

Hi, I have tried in different ways and also look through the help Forum but no luck so far and that why posting this question here. I have written almost the same code as instructor Dave have shown in the Video but I am getting error and when I search for student in the prompt , it shows: student not found in the student list, even though the student is there in the Arraylist, When I search for “list”--- it doesnot shows me anything. Also my while loop---- While(true) ------ given me error as it shows : “ no-constant-condition ( ESLint) Unexpected constant condition”. And last but not least, In my browser console it shows: “Failed to load resource: the server responded with a status of 404 (Not Found)” Can please anyone tell what mistakes I have made which is giving me just error and not giving the same output as teacher Dave? Thanks in Advace !!!! Note: working with visual studio community editor 2017

index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Objects Examples</title>
    <link rel="stylesheet" href="CSS/objectStyles.css">
</head>
<body>
    <h1>Objects Examples</h1>
    <div id="output">

    </div>
    <!--
        <script src="JS/objExamples.js"></script>
        <script src="JS/twoDArrayQuizWithObj.js"></script>
     -->

    <h1>Objects Examples: Students</h1>
    <div id="output1">

    </div>
    <script src="JS/studentObjChallenge.js"></script>
    <script src="JS/studentObjReport.js"></script>
</body>
</html>

Getting Error on while (true ) Tried to declare first but still not working

var message = '';
var student;
var search;
//var continueSearch = false;

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


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



while (true ){
    search = prompt("Search student records: Type a name[ayesha], or type 'quit' to end or 'list' to see all students ");
    if (search === null || search.toLowerCase() === 'quit') {
        break;
    } else if (search.toLowerCase() === 'list') {
        print(students.join(', '));
    } 
    for (var i = 0; i < students.length; i += 1) {
       student = students[i]; // just looping through the indexes ( like addresses)
       if (student.name.toLowerCase() === search.toLowerCase()) { // then check if Ayesha found in any of these index
                //continueSearch = true;
                message = getStudentReport(student);
                print(message);
         } else {
             print(search + ' is not in the Student List.');
         }
        }
    }
// Array object:
var students = [
    {
        name: "Ayesha",
        track: "iOS developer",
        achievements: 500,
        points: 350
    },
    {
        name: "Sara",
        track: "Front-end Developer",
        achievements: 2500,
        points: 2000
    },
    {
        name: "Adil",
        track: "Software-Developer",
        achievements: 5000,
        points: 4000
    },
    {
        name: "Danish",
        track: "Software Engineer",
        achievements: 3500,
        points: 3000
    },
    {
        name: "DR Bill",
        track: "Web design",
        achievements: 3500,
        points: 3000
    }

];

3 Answers

Patricia Hector
Patricia Hector
42,902 Points

Hello there. This is going to be long, so let's go step by step.

1-You need to load your scripts synchronistically, first the file which has the info about the students and then the other file with the logic of your application, and this is because your application needs to see/use students array.

2-You are probably getting a 404 error because of the file styles.css. Check if this one exists and if it does check its path (href attribute).

3-We will encounter one problem with the browser while working with this so, see this link for the teacher's explanation.

4-The browser we can use is Mozilla Firefox, it will load the page with infinite loop correctly. One error I found is in the "for" loop, that "else" statement must not be there. You are basically saying if the first element is not equal to "search" variable, then "else" statement will happen and you will be printing the message 'is not in the Student List'. Remember if-else work like that, if the "if" statement is not true, the "else" statement will occur, and if the "if" statement is true, "else" won't happen. So taking that into consideration, a couple of things changed.

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


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


function getStudentReport(student) {
    var report = '<h2>Student: ' + student.name + '</h2>';
    report += '<p>Track: ' + student.track + '</p>';
    report += '<p>Achievements' + student.achievements + '</p>';
    report += '<p>Points: ' + student.points + '</p>';
    return report;
}
function getAllStudents(){
    var array="";
    for(var i = 0; i<students.length;i+=1){
        array += getStudentReport(students[i]);
        array += "</br>"
    };
    print(array);
}

function findingStudent(student){
    //this function follow the same idea of the "for" loop you had inside the while loop
    //and when you find the student you will return it

    var inform;
    for(var i = 0; i < students.length; i+=1){
        if(student === students[i].name.toLowerCase()){
            //this step is important, remember you are working with an array of objects
            //if you try to print students[i] you'll get something like this [Object object]
            //so you need to get inside your object by using its properties "student.name" 
            //"student.track" etc. And that's exactly what getStudentReport() does.
            inform = getStudentReport(students[i]);
            return inform;
        }
    }
    //if the name doesn't exist you will report it
    inform = "The name " +student+" is not in the database";
    return inform;
}

//findingOneStudentOrMore() function is for repetitive students if you are going to use it
//you need to comment findingStudent() function and its call in the while loop
//this function follow the same logic of findingStudent(), but this time you can not break
//the loop when you find one student, this time you need to go until the end.
//the boolean "foundIt" will let you know if you did find one or more students with
//the same name

/*
function findingOneStudentOrMore(student){
    var inform = "";
    var foundIt = false;
    for(var i = 0; i < students.length; i+=1){
        if(student === students[i].name.toLowerCase()){
            inform += getStudentReport(students[i]);
            inform += " </br>";
            foundIt = true;
        }
    }
    if(foundIt){
        return inform;
    }
     inform = "The name " +student+" is not in the database";
    return inform;
}*/

while(true){

    search = prompt("Search student records: Type a name, or type 'quit' to end or 'list' to see all students ");

    if( search === null || search.toLowerCase() === 'quit' || !search){
        print("Come back soon");
        break;
    }


    if(search.toLowerCase() === 'list'){
        getAllStudents();//
        break;
    }

    message = findingStudent(search.toLowerCase());
    //message = findingOneStudentorMore(search.toLowerCase());
    print(message);
}

5-I hope this helps, better wishes and keep coding.

Anik Devaughn
Anik Devaughn
7,751 Points

Patricia , thank you so much for your help I really appreciate it. I have two more thing to ask you if it is OK, First, when I run the same code ( your one) in the Google Chrome then i get " Comeback soon" behaviour , like trying to find student name "Ayesha" and its response is : "Come back soon" , But the same code is working fine in Firefox. Why is that? Ofcourse it has to do with the browser but why the same code is not working in Chrome? Any clue from our side. Secondly , I am trying to learn Javascript and want to master myself in JavaScript language. But sometimes it so hard to get or understand the code or writing functions. What good Advice I can get from you so I can be better in writing Code. Thanks again for all your help!

Patricia Hector
Patricia Hector
42,902 Points

I remember when I started in this world just a couple of years ago. I asked quite the same question to the ones, I thought, for their experience, they were able to have the answer; they only said, everyone can and should learn how to code, and the only way to do it is by coding...I was really disappointed, I wanted the final guide, the magic key, the shortest path to just with a blink go from point A to point B. There is not such a thing, but a process, a meticulous procedure you have the power to lead. I know the content out there is overwhelming, too many things to do, too many languages to conquer, too many frameworks or libraries to master, but here is when in MY OPINION you should stop and think. What exactly do you want? Where do you see yourself in the next months or years? Doing the design of a website, working with database and managing information, creating new games... Pick a path and remain focused, it will have ups and downs but like everything in life, so for those hard times take a break, hang out, eat, sleep... and then come back and keep coding. Our community is extremely friendly and they will be glad to help you out any time you are dealing with a problem. The tracks on Treehouse are very helpful and well organized and a couple of them are about JavaScript. Go from the easiest to the hardest, don't be in a rush, take your time and enjoy, for people outside our world we are literally wizards, so let that feeling helps you keep going and if you can help somebody else in the process even better.

PS: About the problem with Chrome, it's out of my understanding, but apparently:

"browsers wait until the loop finishes and then they print to the window. So, you'll see a blank page until you type quit in the prompt window — then you'll see all the output printed to the screen."

Dave McFarland

Anik Devaughn
Anik Devaughn
7,751 Points

Thanks alot Patricia for the good advice. I have decided to Master myself in Javascript and from there I can think of something else. But for now I really want to be good in this language and get a decent job so I can gain some experience on it. Thanks again :)

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width", initial-scale="1.0">
    <title>Treehouse Community Forum Help</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/styles.css">
  </head>
  <body>
    <!-- the following div will have the id of 'div', and will be a placeholder for our 
           script to run in the innerHTML property of our div. -->
    <div id='div'>
    </div>
    <script src="js/scripts.js"></script>
  </body>
</html>
/*
Goal objectives correspond to the script number references.

The goal is to create a program that: 

  1)  contains a print function that will write to the innerHTML of a div element.
  2)  contains a print student report function that returns the value of a student's data.
  3)  contains an array of objects; these objects will hold the student's data.
  4)  contains a variable to hold the value of a message, so that I can build a
         message and send the complete message to the print function.
  5)  contains a search variable, via the user prompt dialogue.  It sets the
         user response equal to the search variable.
  6)  contains an empty array variable, from which we will add the student id's;
         later we will compare the search-for id with the built-up id array.
  7)  contains a student variable to pass to the student report function.
  8)  contains a while loop so that the program can search multiple student's
         data, until the user types quit, or the null
         is invoked via the cancel button on the prompt dialogue box.
  9)  contains a for loop that creates a new array of id values to compare
         against user response via prompt.
  10)  contains an indexOf method in case what the user entered was not in the
         array of student ID's.
  11)  contains a for loop to cycle through all of the users ID's and prints out
         those records that have matching user ID's.
*/


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

// 2)
function getStudentReport(student) {
  var report = 'ID: ' + student.id + '<br>';
  report += 'Name: ' + student.name + '<br>';
  report += 'Track: ' + student.track + '<br>';
  report += 'Achievements: ' + student.achievements + '<br>';
  report += 'Points: ' + student.points + '<br><br><br>';
  return report;
}

// 3)
var students = [
  {
    id: 1,
    name: 'matt',
    track: 'Front-End Design',
    achievements: 30,
    points: 2456
  },
  {
    id: 2,
    name: 'matthew',
    track: 'IOS Design',
    achievements: 32,
    points: 3400
  },
  {
    id: 3,
    name: 'matty',
    track: 'Back-End Design',
    achievements: 33,
    points: 3450
  }
];

// 4)
var message = '';

// 5)
var search;

// 6)
var studentId = [];

// 7)
var student;

// 8)
while (true) {
    // gathering the student response in the form of the prompt method.
    search = prompt("Enter student Id. Type 'quit' to exit.");
    // outlining the text and or methods to end the program.
    if (search.toLowerCase() === 'quit' || search === null) {
      break;
    }
    // converting the string response for prompt to an integer, as the id
    // is an integer data value.
    else {
      search = parseInt(search);
    }
    // building an array, of which we will compare user response via
    // the search variable we gathered using the prompt method.

// 9)
    for (i = 0; i < students.length; i += 1) {
      studentId.push(students[i].id);
    }

/* 10)
        comparing the index value of the prompt response (search) against the
        array position of the studentId array.  If the search index is not in
        the array, then the script outputs the message.
*/

      if(studentId.indexOf(search) === -1) {
        message += "ID " + search + "  is not an ID in our database. Please ";
        message += "enter a valid ID, or type 'quit' to exit.<br><br><br>";
        print(message);
      }
      else {
/* 11)   
      else, the script looks for the search value in the array index and
      outputs the array record for the searched for student.
*/
        for (i = 0; i < students.length; i += 1) {
          student = students[i];
          if (student.id === search) {
            message += getStudentReport(student);
            print(message);
          }
        }
      }
}