Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrow function runs perfect without curly braces. Added curly braces{ return } and it breaks [duplicate]

Tags:

javascript

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

} 
like image 774
Thomas_da_tank Avatar asked Jan 27 '23 20:01

Thomas_da_tank


2 Answers

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

} 
like image 122
Pointy Avatar answered Jan 29 '23 09:01

Pointy


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

} 
like image 28
Bon Andre Opina Avatar answered Jan 29 '23 11:01

Bon Andre Opina