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 Solution

C H
C H
6,587 Points

My code keeps crashing TTT and the javascript console and I can't figure out why it's not working.

I can't figure out what's wrong with my code. I got the code to run in the console when I used console.log() inside of the second function where the 'text' variable is now. I then replaced console.log() with the 'print' function, however this didn't work. This is when I tried to concatenate to an empty string variable, 'text', before calling the function. However, it's still not working for me. Please help!

  var text= ' ';

//same function as used by instructor
  function print(message) {
    var outputDiv = document.getElementById('output');
    outputDiv.innerHTML = message;
  }

//loops through array writing it to variable text
  function textList(array) {
    for (var i= -1; up= array.length; ++i<up) {
      for(var key in array[i]) {
        if (key === 'name') {
          text += '<h2>', key, ': ', array[i][key],'</h2>';
        }
        else {
          text += '<p>', key, ': ', array[i][key],'</p>';
        }
      }
    }
  }

  textList(students);
  //for testing purposes, would be replaced with: print(text);
  console.log(text);
C H
C H
6,587 Points

Here's the fixed code for anyone curious:

  var text= '';

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

  function textList(array) {
    for (var i= -1, up= array.length; ++i<up;) {
      for(var key in array[i]) {
        if (key === 'name') {
          text += '<h2>' + key + ': ' + array[i][key] + '</h2>';
        }
        else {
          text += '<p>'+ key + ': ' + array[i][key] + '</p>';
        }
      }
    }
  }

  textList(students);
  print(text);

1 Answer

You are using your first for loop incorrectly, the second part should be a condition statement that looks something like i < array.length... here is a sample structure for a for loop

for (var i = 0; i < 10; i++) {
    //loop code
}

This loop will run 10 times, your code is crashing because you have an infinite/invalid loop.

C H
C H
6,587 Points

Thank you, I now have gotten everything working with some screwing around.