Why would innerHTML output commas?

I have an array of objects but the number of objects varies, so I am using a for loop to create li tags:

let scaleDeg = []
for (let i = 0; i < result[0]["scales"].length; i++) {
  scaleDeg.push(`<li>` + Object.keys(result[0].scales[i]) + ": " + Object.values(result[0].scales[i]) + `</li>`)

Above that loop I set a variable scaleDegrees to an empty string and then I:

scaleDegrees = scaleDeg
document.getElementById('scale-degrees').innerHTML = scaleDegrees;

For some reason, I am getting a comma as a block element in between each list item, but NOT after the last one. It looks similar to the array of objects:

	"Chord": "maj",
	"Intervals": ["1", "3", "5"],
	"steps": [0, 4, 7],
	"Tendency": ["I", "IV"],
	"scales": [
		{ "Major Scale": ["1st", " 4th", " 5th"] },
		{ "Minor Pentatonic": ["2nd"] },
		{ "Blues Scale": ["2nd"] },
		{ "Harmonic Minor": ["5th", "6th"] },
		{ "Melodic Minor": ["4th", "5th"] },
		{ "Augmented": ["1st", "3rd", "5th"] },
		{ "HW Diminished": ["1st", "3rd", "5th", "7th"] },
		{ "Major Bebop": ["1st", "4th", "5th"] },
		{ "Minor Bebop": ["3rd", "5th", "8th"] }

Does anyone know why I would be getting this comma in my HTML, or more importantly, what can I do to get rid of it? Here are 2 screenshots. The first one is the console:


Here is the page:


scaleDeg is an array. innerHTML takes a string. So JS is converting the array to a string for you. It is basically doing this:

['a', 'b', 'c'].toString()

Which results in:


Also, the following:

scaleDegrees = scaleDeg

does convert it to a string, but using the same toString() method. So you still get the inserted commas.

1 Like

So in here, how are you expecting scaleDegrees to output, when you set that content? What do you think that variable contains?

I tried to skip that and just use scaleDeg as the variable for innerHTML but I go the same result. So it the problem that it is a string?

I just logged scaleDegrees for a new chord and got the following:

0: "<li>HW Diminished: 1st,3rd,5th,7th</li>"
1: "<li>Major Bebop: 3rd</li>"

So that should be what is outputting to the page but I’m getting I think the commas associated with the scale array (I think).

1 Like

Nah. Try explicitly telling JavaScript how you want those elements joined.


If you don’t stipulate how to perform the join (which is what toString is doing), it will default to a comma. But you can tell it what to use instead.


scaleDegrees = scaleDeg.join("")

I would buy uou a beer or a cup of coffee if I could - thanks!

1 Like

No worries, glad you figured it out. And keep the devdocs link, it’s a truly useful reference site

I created a huge JavaScript Cheatsheet GitHub repo and I have links to all the MDN docs pages as well aas eamples. I just didn’t realize that it was a string. I should have used typeof on it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.