Home > Back-end >  undefined is appending in top of documnet
undefined is appending in top of documnet

Time:02-13

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)

CodePudding user response:

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>`
}

CodePudding user response:

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`);
});

  • Related