3

I am wanting to create an array of objects and display a specific list of properties when certain conditions are met.

The following code does what I want when I print it to the console or use document.write.

var people = [{ 
    firstName: 'John',
    lastName: 'Doe',
    age: 23,
    },{ 
    firstName: 'Jane',
    lastName: 'Doe',
    age: 53,
    }]

    for(i = 0; i < people.length; i++){
        if(people[i].age < 65){
            document.write(people[i].firstName + ' ' + 
            people[i].lastName + ' has printed to document. <br>');             
        }
    }

But when I go to run the code in the browser, using document.getElementById, only the last item is displaying.

for(i = 0; i < people.length; i++){
    if(people[i].age < 65){
        result = 'Only ' + people[i].firstName + ' ' + 
            people[i].lastName + ' is printed to document. Why?';               
    }
}
document.getElementById('names').innerHTML = result;

Could someone explain to me why all items appear using document.write? While only the last item appears when using document.getElementById?

1 Answer 1

3

The issue is in this line:

result = 'Only ' + people[i].firstName + ' ' + 
        people[i].lastName + ' is printed to document. Why?';

Because you're assigning the message string to result variable. Since you are in a loop, the result variable will just hold the last value.

You have to concat the message to result variable.

for(i = 0; i < people.length; i++){
    if(people[i].age < 65){
        result += 'Only ' + people[i].firstName + ' ' + 
            people[i].lastName + ' is printed to document. Why?';               
    }
}

Also, you can use string templates for formatting the message.

result += `Only ${people[i].firstName} ${people[i].lastName} is printed to document. Why?`;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.