How to add template literals with a forEach in it with JavaScript?

Sometimes, we want to add template literals with a forEach in it with JavaScript.

In this article, we’ll look at how to add template literals with a forEach in it with JavaScript.

How to add template literals with a forEach in it with JavaScript?

To add template literals with a forEach in it with JavaScript, we should replace forEach with map.

For instance, we write:

const arr = ['apple', 'orange', 'grape']
const options = arr
  .map(a => {
    return `<option value='${a}'>${a}</option>`
  })
  .join('')
const str = `<select>${options}</select>`
console.log(str)

to call arr.map with a callback that maps the values in arr to an option element string.

Then we call join to combine the strings from the array returned by map into a single string.

Next, we put the options string into the str template literal.

As a result, str is:

<select><option value='apple'>apple</option><option value='orange'>orange</option><option value='grape'>grape</option></select>

Conclusion

To add template literals with a forEach in it with JavaScript, we should replace forEach with map.