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 Displaying the Content

Alex Hort-Francis
Alex Hort-Francis
17,074 Points

Interested in the rules for how arrays coerce to HTML elements (data.map to innerHTML)

I notice that within the generateOptions() function, we declare the variable options, which is an array created through map() (map() returns a new array).

options is then used to populate the select element.

Later to remove the commas, Guil uses join() to turn the array into a single concatenated string; but before then the innerHTML value of the select element points directly to an array.

This still renders on the page, though, so there must be some convenient coercion going on 'under the hood' to allow the array (which is an object) to be used for a bunch of option HTML elements.

Thought this was interesting, and I wonder about the rules and best practice around this, if anyone has any further thoughts?

2 Answers

Steven Parker
Steven Parker
230,274 Points

The array doesn't get converted into an element, but innerHTML is only expecting a string.

When you use an object where a string is expected, the system will see if the object has a "toString" method, and invoke it for you if it does. This is what is happening in the example prior to the addition of the "join" method. The "toString" method of an array converts its items into a comma-separated list.

Alex Hort-Francis
Alex Hort-Francis
17,074 Points

Steven Parker: Excellent! That makes complete sense, thanks for explaining that.