JavaScript30 - 6 Ajax Type Ahead
Tags: javascript, beginners, learning, javascript30
Published: 2024-06-21 16:59:12

Hello and welcome back to another awe-inspiring addition to my experiences with Wes Bos's [JavaScript30!](https://javascript30.com/)  This time I attacked the Ajax Type Ahead challenge and let's just say, even after completing the challenge, I still have close to ZERO idea what "Ajax Type Ahead" means.  I mean...type ahead makes sense but...anyway I digress.

I have all but decided that moving forward I will be coding along with Wes during these challenges and then rewatch the video as many times as it takes for me to understand what we actually did.  There were more than a few parts of this challenge where I had basically no idea what we were even typing out or why.  There was even one part where Wes made a joke and I wasn't sure if he was being serious or not because, as it turns out, my base knowledge is no where near where I thought it was.

## The Challenge

So the challenge itself was for us to take data in the form of an array from one specific location (in this case it was a .json file) and then make a way to search through the data while showing a complete list of any item in the array based on the letters typed while highlighting said letters in the list in real time. wow. Oh did I mention the list consisted of cities, the states they are located in and their population?  Because that's pretty important.

![The layout of the page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d614au0m9ot8mxde6we7.png)

As you can see the list works.  You cannot see it working in real time but of course, it does.  Wes being Wes he did already set up the CSS and basic HTML elements so the focus of the challenge was just the JavaScript.  I do long for the days where I could flaunt my HTML and CSS skills just to give myself that little confidence boost before a lesson.  Also, I still find myself struggling with reading someone else's code as opposed to writing my own from scratch.

```JS
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

const cities = [];
fetch(endpoint)
  .then(blob => blob.json())
  .then(data => cities.push(...data));
```

There were quite a few pieces of JavaScript that I have never encountered before.  Such as `fetch` which grabs data from an outside source with a `promise`.  Which makes sense when you think about how `promise`'s work and how it can relate to `.then()`.  Now what I just said I can barely explain at the moment.  But I am starting to understand how and why they work and work together...or at least I think I am.  As it turns out getting the information was the easy part and it was about time to get thrown into the deep end.  

```js
function findMatches(wordToMatch, cities) {
  return cities.filter(place => {
    // here we need to figure out if the city or state matches what was searched
    const regex = new RegExp(wordToMatch, 'gi');
    return place.city.match(regex) || place.state.match(regex)
  });
}
```

This introduced other concepts I haven't encountered before, such as: `RegExp`, word matching with `.match` and `'gi'` (global insensitive).  The `'gi'` was where he made his joke about things being insensitive...which I DID NOT KNOW was a joke at first and also didn't realize it was referring to case sensitivity and looking back at it makes me feel pretty silly.  Much like everything else introduced here I can almost explain each of these concepts but I am starting to grasp what they do and why.

```js
function displayMatches() {
  const matchArray = findMatches(this.value, cities);
  const html = matchArray.map(place => {
    const regex = new RegExp(this.value, 'gi');
    const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
    const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
    return `
      <li>
        <span class="name">${cityName}, ${stateName}</span>
        <span class="population">${numberWithCommas(place.population)}</span>
      </li>
    `;
  }).join('');
  suggestions.innerHTML = html;
}
```

Now that we could search through the data it was time to display that on the html.  Although it seemed like a lot at first, looking over it now I do see the purpose for each line of code and what they did.  One thing that I thought was crazy was the concept of replacing each character in the data with a highlighted version of the same character based on what was typed in the search bar.  To me highlighting a word or character is exactly that.  Basically taking a hypothetical highlighter and then in turn highlighting words in real time on the screen...OF COURSE this is not how it works but that's just how I have processed it for my last 35 years of life.  That being said I did find an issue with the finished product of this challenge based on the concept of ignoring case sensitivity and replacing characters based on the search bar, see the image below.

![example of case sensitivity issues](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/efw9st0x74zb7v399lx1.png)

As it turns out replacing a character with the same exact character but "highlighted" while ignoring case sensitivity while searching itself can case some issues.  You can make some pretty hysterical results while messing with upper and lowercase letters in the search bar and then changing the results as it updates in real time.  Yeah, okay, so the search function doesn't break and still works exactly how we programmed it to work but I feel like it is worth mentioning/revisiting this "bug".

## One More thing

I feel the need to mention one last part of this challenge.  There was a blink and you miss it part that I had to rewatch about 5 times before even knowing what happened and I still do not really understand of the syntax used here.  

```js
function numberWithCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
```
This is nuts.  All this did was add a comma to the population numbers while searching.  But when he added this to the code just by being so nonchalant and saying "yeah, you can just find this and copy it".  Yeah I get it...I have done that many times before...but at least then I broke down the code piece by piece to ensure I also understand what I am doing and calling...but that...that thing scares me.

## Conclusion 

Well...I did it...or more so Wes did it and I followed along.  But this is another challenge for the history books.  Of course there are other parts of this that I left out but if you want to know more why not give it a try yourself!  Much like the last few challenges I have done in this course I do not feel as accomplished as before, but I do know I am getting practice.  Given the free time I have at the moment I know this is exactly what I should be doing.  I just can't wait for when I can actually take more time and focus on coding the way I would like to.

Tune in next time for another jaw-dropping addition to my journey into Wes Bos's [JavaScript30!](https://javascript30.com/) where I will be tackling: Array Cardio Day 2!
![array cardio day 2!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gga4v0y0i0ys3mkkdag3.png)