'undefined is appending in top of documnet

Trying to create a page using Javascript. when I try to append HTML into the main div I can see the HTML but I'm seeing undefined in the first line of the document.

const letterArry = [
  { name: 'A', id: 'a', soundtype: 'one' },
  { name: 'B', id: 'b', soundtype: 'two' }
];

let eleOne = document.getElementById('app');

eleOne.innerHTML = letterArry.map((i) => {
  let html;
  return (html += `<div class={alphabets}>
                      <ul>
                          <li id= ${i.id}>
                              ${i.name} ${i.soundtype} 
                          </li>
                      </ul>
                  </div`);
})```


All I'm trying to do is create a list item, I don't have any console logs in the file or browser.


can someone please help to understand why I'm seeing undefined in the top line? 

[code snippet](https://stackblitz.com/edit/js-jfz9dk?file=index.js)


Solution 1:[1]

You have 2 problems.

  1. map function returns an array, so instead of an html string, you have an array at the end.

  2. Since you create html variable inside the map function, you don't concatinate anything. Everytime you have a new html variable with no value.

What you want can be done by map function, but reduce function suits better.

eleOne.innerHTML = letterArry.reduce(
  (previous, current) => previous + makeString(current), ''
);

const makeString = (current) => {
  return `<div class={alphabets}><ul>
    <li id= ${current.id}>${current.name} ${current.soundtype}</li>
  </ul></div>`
}

Solution 2:[2]

All you need is a function that maps over your data to create an array of list items (which you then join into an HTML string), and then you can add the result of calling that function to a ul element.

const arr=[{name:"A",id:"a",soundtype:"one"},{name:"B",id:"b",soundtype:"two"}];

const eleOne = document.getElementById('app');

function getItems(arr) {
  return arr.map(obj => {
    return `
      <li id= ${obj.id}>
        ${obj.name} ${obj.soundtype} 
      </li>`;
  }).join('');
}

eleOne.insertAdjacentHTML('beforeend', `<ul>${getItems(arr)}</ul>`);
<div id="app"></div>

Additional documentation

Solution 3:[3]

return value directly HTML at start is undefined like this

const letterArry = [
  { name: 'A', id: 'a', soundtype: 'one' },
  { name: 'B', id: 'b', soundtype: 'two' },
];

let eleOne = document.getElementById('app');


eleOne.innerHTML = letterArry.map((i) => {
  return (`<div class={alphabets}>
                      <ul>
                          <li id= ${i.id}>
                              ${i.name} ${i.soundtype} 
                          </li>
                      </ul>
                  </div`);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bulent
Solution 2 Andy
Solution 3 Abbas Hussain