Skip to content

Instantly share code, notes, and snippets.

@wiledal
Last active March 9, 2023 20:57
Show Gist options
  • Save wiledal/6e1b7e4eb57f22c38cecd70600b34a40 to your computer and use it in GitHub Desktop.
Save wiledal/6e1b7e4eb57f22c38cecd70600b34a40 to your computer and use it in GitHub Desktop.
Template Literals example: for each
/*
Template literals forEach example
Using Array.map(), we can create a forEach within template literals.
*/
var items = [
{ name: 'Teddy' },
{ name: 'Dolores' },
{ name: 'William' },
{ name: 'Bernard' }
]
element = document.createElement('div')
element.innerHTML = `
<h1>This element has items</h1>
${this._items.map((item, i) => `
<div>
I am item number ${i < 10 ? '0' + (i + 1) : i + 1}.
My name is ${item.name}.
</div>
`.trim()).join('')}
`
/*
Results:
<div>
<h1>This element has items</h1>
<div>I am item number 01. My name is Teddy.</div>
<div>I am item number 02. My name is Dolores.</div>
<div>I am item number 03. My name is William.</div>
<div>I am item number 04. My name is Bernard.</div>
</div>
*/
@oneezy
Copy link

oneezy commented Mar 7, 2018

Line 16

${this._items.map((item, i) =>

should be

${this.items.map((item, i) =>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment