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

HTML

Why set the value of select.innerHTML to an array of strings

const options = data.map(item => `<option value = "${item}">${item}</option>`); 
select.innerHTML = options;

As is shown above, options is an array of strings and is directly assigned to select.innerHTML. When inspecting I found in my html file there are " , " between<option> tags like:

<select class="u-full-width" id="breeds">
    "
    <option value="affenpinscher">affenpinscher</option>
    ","
    <option value="african">african</option>
    (.etc)
</select>

and it should be like:

<select class="u-full-width" id="breeds">
    <option value="affenpinscher">affenpinscher</option>
    <option value="african">african</option>
    (.etc)
</select>

I am just wondering if those unnecessary "" and , matter in the HTML file, and is it better to remove those using loops or some other techniques instead of setting the innerHML to an array of strings directly.

1 Answer

Steven Parker
Steven Parker
231,248 Points

You might want to convert the array into a single string to avoid the comma insertion:

select.innerHTML = options.join("");

You could also create "options" as a single string to begin with using "reduce" instead of "map":

const options = data.reduce((out, item) => `${out}<option value = "${item}">${item}</option>`, "");
select.textContent = options;

Thank you, this is very useful! I posted it since I saw a line of code like this in the course 'Asynchronous Programming with JavaScript'. Though it made html look slightly weird but it works properly. I edited my question so the codes are easier to read. So I am wondering that, does it matter whether the double quotation marks and commas are avoided? Cause that's exactly what the teacher wrote in the video.

Steven Parker
Steven Parker
231,248 Points

Perhaps you'd post a link to the video (and a time reference). But a <select> should only contain <option> or <optgroup> elements, so I would expect that creating child text nodes (as the commas would do) should be avoided.