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

Mark Brady
Mark Brady
6,239 Points

*[SOLVED]* -- Undefined in my code and only Dave is repeated not others

Only Dave is repeated and there is a couple undefined errors in my print out. Can someone look at my code and tell me what I'm doing wrong?

Thank you for your time fellow coders!

var message;
var html;

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

for (var i = 0; i < students.length; i++) {
  html += "<h2>Student: " + students[0].name + "</h2>";
  html += "<p>Track: " + students[0].track + "</p>";
  html += "<p>Points: " + students[0].points + "</p>";
  html += "<p>Achievements: " + students[0].achievements + "</p>";
  message = html;

var students = [ 
    name: 'Dave',
    track: 'Front End Development',
    achievements: 158,
    points: 14730
    name: 'Jody',
    track: 'iOS Development with Swift',
    achievements: '175',
    points: '16375'
    name: 'Jordan',
    track: 'PHP Development',
    achievements: '55',
    points: '2025'
    name: 'John',
    track: 'Learn WordPress',
    achievements: '40',
    points: '1950'
    name: 'Trish',
    track: 'Rails Development',
    achievements: '5',
    points: '350'
<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <link rel="stylesheet" href="css/styles.css">
<div id="output">

<script src="js/students.js"></script>
<script src="js/students_print.js"></script>
Mark Brady
Mark Brady
6,239 Points

Okay, I figured out my repeating issue. I didn't have the [i] variable after "students" in my loop.

So, that is solved, but I don't understand the undefined??

Mark Brady
Mark Brady
6,239 Points


I figured the undefined issue, too.

The "html" var at the top of the script needs to equal an empty string ( var html = ""; ).

Have fun coding guys and gals and don't give up!

1 Answer

Adrian Thomas
Adrian Thomas
1,572 Points

Thanks for this. I was getting pretty confused with this challenge. I got hung up on trying to print both the property names AND the property values. Looking at your solution, instead of trying to get the property name to appear, it's simpler to just type in a property name like "Student".

Upon further reflection, even if I were to get it right, the property name for the student is actually "name" and not "student", so I could have had to change that property name to "student" anyway.

Tried your solution using a for in loop and the results were the same.

for (var i in students) {
  html += "<h2>Student: " + students[i].name + "</h2>";
  html += "<p>Track: " + students[i].track + "</p>";
  html += "<p>Points: " + students[i].points + "</p>";
  html += "<p>Achievements: " + students[i].achievements + "</p>";

Thanks for your thread. Guess I should really use KISS more often. My brain would hurt a lot less.