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

I don't understand why my script generates an empty <li> tag at the beginning of the HTML list ?

var students = [
{
    name: 'John',
    track: 'javascript basics',
    achievements: 5,
    points: 200

},
{
    name: 'Vlad',
    track: 'python',
    achievements: 10,
    points: 3000

},
{
    name: 'Leigh',
    track: 'databases',
    achievements: 4,
    points: 444

},
{
    name: 'Sushi',
    track: 'css',
    achievements: 2,
    points: 100

},
{
    name: 'Gizmo',
    track: 'php',
    achievements: 9,
    points: 2000

}
];
var result;

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

result = "<ol>";

function loopArray (array) {
    result += "<li>";
    for  (var i = 0; i<array.length; i += 1 ) {

        result += "<li>"; 

        for (var key in array[i]) {
            result += key + " : " + array[i][key] + "</br>";
        }

        result += "</li>"
    }

    result += "</ol>"
    print(result)
}

loopArray(students);

Sorry, I just realised my mistake.

It's because I'm opening but not closing a list item outside the "for" loop that iterates through the array.

Sorry!

What was your intention with opening a list item before the loop? Were you trying to wrap all the list items from the loop in another list item?

1 Answer

Hi Tiberiu,

At the start of your function, before the loop, you're concatenating an opening li tag. This would add an empty li at the beginning.

Your for loop is already adding opening and closing li tags around each student so you don't need that initial one before the loop.

It was only after I posted the question I realised what was happening.

Thanks for you for taking the time to explain.

Initially I wanted each student to be an individual list with each key-value pair wrapped inside the an li tag. However, I gave up on this idea as I thought I was overcomplicating the task. The li before the loop was just residual code which I forgot to remove.