
A few months back this year, while learning about the new arrow function and building a small application. I got caught out by the return keyword.
I was trying to create a function where users can input a value into the search box. For each value match, we will get HTML elements rendered to the DOM.
The function looks 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
}
I know that using an arrow function to return simple values we can omit the curly braces. But I wanted to experiment with what happens when we use curly braces.
We know with curly braces we must use a return keyword. Which is exactly what I have done in the above function. The code would not run. Why did the code not run?.
Well, it turned out that with Javascript engine if you place the return keyword on its own line of code as I did. It will stop running and parse nothing since there is nothing after the return keyword.
I found the solution after a few hours of researching and asking questions on forums. The solution was simple. We need to bring values we want to return up to the same line where the return keyword resides, 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
}
If you notice all I did was to bring the beginning of template literal with the HTML element inside it up to the same line of the return keyword. That worked.
Or we can omit the entire curly braches with the return keyword because arrow function implicitly returns all values for us anyway. Like the solution below.
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
}
Javascript veterans say this language will trip you up with all its quirks and hidden traps, this was my first taste of it. It sounds crazy but it makes me want to dig deep into this language to really learn more about it.
See you next time.