JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

Josie Nagy
Josie Nagy
14,267 Points

Undefined issue

Hi everyone! I'm stuck trying to understand what's going on here.

My issue: instead of displaying the name, as it should, it just shows me this in the browser:

Student: undefined

Here is my solution so far:

var message = "";
var student;

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

for (var i = 0; i < students.length; i += 1) {
  var student = students[i]; 
  message += '<h2>Student: ' + students.name + '</h2>';
}

print(message);

My JSON file:

var students = [
  {
    name : "Josie",
    track : "Python Development",
    achievements : 108,
    points : 11500
  },
  {
    name : "Caleb",
    track : "iOS Development with Swift",
    achievements : 68,
    points : 18099
  },
  {
    name : "Andal",
    track : "Design Thinking",
    achievements : 73,
    points : 9960
  },
  {
    name : "Tara",
    track : "Front End Development",
    achievements : 530,
    points : 40021
  },
  {
    name : "Jonathan",
    track : "JavaScript Basics",
    achievements : 44,
    points : 2504
  }
];

My index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Students</title>
    <link rel="stylesheet" href="css/styles.css">
  </head>
  <body>
    <h1>Students</h1>
    <div id="output">

    </div>
    <script src="./js/student-records.js"></script>
    <script src="./js/students.js"></script>
  </body>
</html>

1 Answer

anthony amaro
anthony amaro
8,296 Points

one issue is that you are trying to get the name from the array not the object

var student = students[i]; 
 message += '<h2>Student: ' + students.name + '</h2>';
// it should be student.name

you are storing the objects in student variable. students is the array. hope this helps

Josie Nagy
Josie Nagy
14,267 Points

Thanks a lot Anthony, yes that was the issue. I understand the difference now.