I'm going through Javascript 30 by Wes Bos.
I'm doing the AJAX type ahead course, and I'm sort of trying to limit the amount of ES6 I do on it, just for the sake of practice.
This is the finished version:
https://codepen.io/Airster/pen/KNYXYN
Note that as you type in a location, the searched value gets highlighted in yellow within the results.
Now the javascript that determines this is the displayMatches function:
var displayMatches = function(){
console.log(this.value);
var matchArray = findMatches(this.value, cities);
var html = matchArray.map(function(place){
console.log(this, place, "test");
var regex = new RegExp(this.value, 'gi');
var cityName = place.city.replace(regex, "<span class='hl'>" + this.value + "</span>");
var stateName = place.state.replace(regex, "<span class='hl'>" + this.value + "</span>");
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${place.population}</span>
</li>
`;
}).join("");
suggestions.innerHTML = html;
}
The issue lies with the function variable html. Currently I have it as:
var html = matchArray.map(function(place){...})
This doesn't work, and I will get undefined in the results.
However, if I change it into an arrow function:
var html = matchArray.map(place => {...})
The function will run and the searched value will get highlighted.
Can someone explain why within this particular context, the arrow function works?
Thanks in advance!
this.valueis only used, consider if you couldn't make it an argument of the method, which would make a lot more sense