How to display array elements via arrow function?

  • 0
    Hello! The question is most likely primitive, BUT ...

    There is an array of words that I get from localstorage ....

    const favorites = JSON.parse(localStorage.getItem('favorites')) ?? []


    Which I am trying to process (select even elements only) and insert into html ...

    const html = renderList(favorites)
    
    this.$el.insertAdjacentHTML('afterbegin', html)


    function renderList(list) {
        if (list.length) {
            return `
            <ul>
               ${list.map((item, i) => {
                    if (i % 2 === 0 || i === 0) {
                        `<li><a href="#" class="js-link">${item}</a></li>`
                    }   
                    }).join(' ')
                }    
                </ul>
    `
        }
        return`<p class="center">Вы пока ничего не добавили</p>`
    }


    So nothing is displayed.

    If ...

    function renderList(list) {
        if (list.length) {
            return `
            <ul>
               ${list.map((item, i) => `<li><a href="#" data-id="${i}"class="js-link">${item}</a></li>`).join(' ')}  
            </ul>
            `
        }
        return`<p class="center">Вы пока ничего не добавили</p>`
    }


    The data is being output, but I cannot process it ...

    What am I doing wrong?
    JavaScript Anonymous, Mar 29, 2019

  • 2 Answers
  • 0
    (item, i) => {
    if (i % 2 === 0 || i === 0) {
    `<li><a href="#" class="js-link">${item}</a></li>`
    }
    }




    This function returns nothing.



    Need

    (item, i) => {
    if (i % 2 === 0 || i === 0) {
    return `<li><a href="#" class="js-link">${item}</a></li>`
    }
    }
    Anonymous

  • 0
    The arrow function is not needed here, you need to read the documentation here.

    You use a map that should return a new element of the array, it does not return anything for you. In addition, if you put an if in the map, it will return either a new array element or undefined, which will also break the logic.

    The arrow function worked for you because there is no need for a return in the short notation which you forgot about.

    Read about reduce, or even better, stupidly open Flenegan and read from cover to cover.
    Ella Edwards

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!