4

I rendered data from my objects to the DOM perfectly by using using arrow function without curly braces.

I tried adding curly braces after the same arrow function. The DOM will not render any data.

CODE WORKS WITHOUT CURLY BRACES AFTER ARROW FUNCTION

function displayMatches () {
    const matchArray = findMatches(this.value, cities)
    console.log(matchArray)
    const html = matchArray.map(place => 
        `<li>
            <span class="name">${place.city}, ${place.state}</span>
            <span class="population">${place.population}</span>
        </li>`
    ).join('')
    suggestion.innerHTML = html

}


THE SAME CODE BREAKS WITH CURLY BRACES AFTER ARROW FUNCTION 

function displayMatches () {
    const matchArray = findMatches(this.value, cities)
    console.log(matchArray)
    const html = matchArray.map(place => {
        return
        `<li>
            <span class="name">${place.city}, ${place.state}</span>
            <span class="population">${place.population}</span>
        </li>`
    }).join('')
    suggestion.innerHTML = html

} 

3 Answers3

4

You're falling victim to a "trap" in the semicolon insertion rules. After a return, a semicolon is assumed if an expression doesn't start on the same line.

If you change your function as follows, it should work:

function displayMatches () {
    const matchArray = findMatches(this.value, cities)
    console.log(matchArray)
    const html = matchArray.map(place => {
        return `<li>
            <span class="name">${place.city}, ${place.state}</span>
            <span class="population">${place.population}</span>
        </li>`
    }).join('')
    suggestion.innerHTML = html

} 
Pointy
  • 405,095
  • 59
  • 585
  • 614
3

What happens is when you use arrow functions with and returning a value with below the return statement like this:

return
`My Statement` // unreachable code

You will get an error. But if you do it like this:

return `My Statement` //reachable code

It should fix your problem if you do it like this:

function displayMatches () {
    const matchArray = findMatches(this.value, cities)
    console.log(matchArray)
    const html = matchArray.map(place => {
        return `<li>
            <span class="name">${place.city}, ${place.state}</span>
            <span class="population">${place.population}</span>
        </li>`
    }).join('')
    suggestion.innerHTML = html

} 
Bon Andre Opina
  • 2,129
  • 2
  • 15
  • 33
1

the lack of curly braces in arrow function, means return the evaluation.

so

    matchArray.map(place => 
      place.state
    )

    // is equal to
    matchArray.map(place => {
      return place.state
    })

i suggest dig deeper into es6 arrow functions to understand better .
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Nikko Khresna
  • 1,024
  • 8
  • 10