Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Alex Francis13,840 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() 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?
Steven Parker216,891 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.