javascripttemplate-literals

Why does a comma appear when I interpolate an array into a template literal?


So I am just labbing a little with template literals and I seem to get a unexpected , in my html output. Anyone could explain to me why these , shows when I use a map?

 this.highscore = [
        {
            "username" : "Thor",
            "highScore": 1002023
        },
        {
            "username" : "Hulk",
            "highScore": 1037465
        },
        {
            "username" : "Superman",
            "highScore": 5948393
        },
        {
            "username" : "Spiderman",
            "highScore": 5949384
        }
    ]

 template() {
    return `high score: ${this.highscore.map(user => `<p>Username: ${user.username} <br> ${user.highScore}</p>`)}`
 }

render() {
    this.innerHTML = this.template()
}

OUTPUT IN HTML

Username: Thor 
1002023

, /* <----- where does this sucker come from? */
Username: Hulk 
1037465

,
Username: Superman 
5948393

,
Username: Spiderman 
5949384

Just a bonus 🦄

Explanation why this occur from T.J. Crowder is correct, he suggested that I should use join and for the fun of it I tagged the template with a custom function to handle it, will leave it here for giggles:

function removeYaOldBugger(strings, personExp, ageExp) {
 return personExp.join("")
} 

template() {
    return removeYaOldBugger`high score: ${this.highscore.map(user => `<p>Username: ${user.username} <br> ${user.highScore}</p>`)}`
}

Solution

  • Because map returns an array, and then ${...} coerces it to string, which uses Array#join, which defaults to using , as the separator between elements. You can fix it by adding .join("") to the end of the map call:

    return `high score: ${this.highscore.map(user => `<p>Username: ${user.username} <br> ${user.highScore}</p>`).join("")}`
    // >>-------------------------------------------------------------------------------------------------------^^^^^^^^^