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 Build an Object Challenge, Part 2

Blake Runyon
Blake Runyon
Full Stack JavaScript Techdegree Student 7,539 Points

Undefined at beginning of list?


Any idea why I'm getting an undefined at the front of this list?

var html;
var students = [
      name: "Sean Flanagan",
      track: "Beginner JavaScript",
      achievements: 252,
      points: 21829
      name: "Richard Johnson",
      track: "Web Design",
      achievements: 15,
      points: 1400
      name: "Robert Walker",
      track: "Learn HTML",
      achievements: 35,
      points: 500
      name: "Joanne Maxwell",
      track: "Front End Web Development",
      achievements: 50,
      points: 3500
      name: "Christine Robinson",
      track: "Learn Java",
      achievements: 72,
      points: 5000

function print() {
    document.querySelector('body').innerHTML = html;

for (var i = 0; i < students.length; i += 1) {
    html += `<p><strong>Student ${i + 1} Info:</strong></p>`;
    name = students[i].name;
    html += `<p>Name: ${name}</p>`;


3 Answers

Grzegorz Zielinski
Grzegorz Zielinski
5,838 Points

It's because at the very beginning of your script you have not defined any value for variable 'html' (var html;), and because of that when you print your message to page you end up with "undefined" word at the beginning of your list (your loop adds all the paragraphs to html which starting value is "undefined" so you and up with something like 'undefined += <p>...</p> etc.).

To make it work you just simply need to define any value, even empty brackets to your html variable:

var html = '';

It will solve the problem.

Because html is undefined when you replace the body with it.

document.querySelector('body').innerHTML = html;

By the way, you overwrite the h1 as well.

My suggestion would be to append instead of overwriting (+= instead of =) and make sure html isn't undefined when you declare it (make it an empty string instead, so var html = '')

Hugo Jeffreys
Hugo Jeffreys
8,505 Points

This solved my issue as well. Many thanks!