"Build a Blog Reader iPhone App" was retired on May 31, 2020.

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

Iterating Through an Object Issue

I am confused by the output for iterating through the object shown below. I am confused as to why the for loop I have is not iterating through each object in the array. Instead, it only writes the last object to the document.

var students = [
    {
    name: 'Chris',
    game: 'Sonic 2',
    points: 15000
    },
    {
    name: 'Stephanie',
    game: 'Sonic 3',
    points: 17500
    },
    {
    name: 'Scooter',
    game: 'Angry Birds',
    points: 18500
    },
    {
    name: 'Sammy',
    game: 'Worms 2',
    points: 8500
    },
    {
    name: 'George',
    game: 'Earthworm Jim',
    points: 99300
    }
];


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

for (var i = 0; i < students.length; i++) {
    print(students[i].name);
}

Output

George

The output for this code confuses me. The for statement should be iterating through every object within the array and displaying all the name properties (Chris, Stephanie, Scooter, Sammy, George). Instead it only displays George.

Would appreciate any clarification as to what is going on here, many thanks.

1 Answer

Hey Chris Feltus,

The problem you're experiencing is that each time the iteration completes, you are replacing what was in the outputDiv with the newest print statement. So, when it gets to the end of the iteration, George is all that remains.

Instead of replacing the content each time, you should instead be adding each additional content to the outputDiv with a += instead of just = like so:

        var students = [
    {
    name: 'Chris',
    game: 'Sonic 2',
    points: 15000
    },
    {
    name: 'Stephanie',
    game: 'Sonic 3',
    points: 17500
    },
    {
    name: 'Scooter',
    game: 'Angry Birds',
    points: 18500
    },
    {
    name: 'Sammy',
    game: 'Worms 2',
    points: 8500
    },
    {
    name: 'George',
    game: 'Earthworm Jim',
    points: 99300
    }
];


function print(message) {
  var outputDiv = document.getElementById('output');
//Added += and " " for spacing at the end
//Output will be: Chris Stephanie Scooter Sammy George
  outputDiv.innerHTML += message + " ";
}

for (var i = 0; i < students.length; i++) {
    print(students[i].name);
}