Search code examples
javascriptes6-map

JavaScript Passing in a function to map();


Can someone please explain how the below code working?

...

articles.map(createArticle).join("\n");

function createArticle(article){
  return `
    <div class="article">
      <h1>${article.news}</h1>
    </div>
  `
}

I understand how map(); works, I just don't understand where it gets article from as its not being passed as an argument to the createArticle function within map();


Solution

  • The createArticle function is actually being passed 3 arguments: the item in the array, the index of the item and the array.

    articles.map(function createArticle(article, i, arr) {
        return `
            <div class="article">
                <h1>${article.news}</h1>
            </div>
        `
    });
    

    Your code is just changing the createArticle function from an anonymous function into a named one.

    articles.map(createArticle);
    
    function createArticle(article, i, arr) {
        return `
            <div class="article">
                <h1>${article.news}</h1>
            </div>
        `
    }
    

    Since parameters don't need to be declared in JavaScript, your code doesn't include the i or arr parameters.

    articles.map(createArticle);
    
    function createArticle(article) {
        return `
            <div class="article">
                <h1>${article.news}</h1>
            </div>
        `
    }
    

    You can see a full explaination and a polyfill (unnecessary these days, but can be helpful when trying to understand a function) on MDN