50 Projects in 50 Days, Day 10: Dad Jokes

50 Projects in 50 Days, Day 10: Dad Jokes

This is the first project of the 50 Projects in 50 Days set to use an external data source. It sends a query to an open API of dad jokes, then displays the result.

An API (application programming interface) is, at the risk of oversimplifying, a way of using data from another part of the web in your own website. In this case, there is a database (a Dad-a-base?) of jokes, and the creators of the database have made it 'open' or freely accessible without having to deal with any kind of encryption or authentication.

What this means from a web developer standpoint is that we can create a web page like the one pictured above, leave space for the content, then use JavaScript to retrieve the content and display it in our own page.

This is fairly simple in HTML. For this page, all it takes is a div with an ID:

<div class="container">
      <h3>
        Don't Laugh Challenge
      </h3>
      <div id="joke" class="joke">
        // Joke Goes Here
      </div>
      <button id="jokeBtn" class="btn">
        Get Another Joke
      </button>
 </div>

The line "// Joke Goes Here" is literally a placeholder for where the text of the joke will be displayed.

I really liked the approach Brad Traversy took in explaining the basics of how to work with APIs, and my intent here is certainly not to undercut his work on that. Suffice it to say that the video for this project alone, in my opinion, justifies the tuition for the course. API use is central to modern web developing.

Of special note in this project is the JavaScript fetch API, and specifically the differences between the .then notation vs. async-await. Both approaches are explained in the video. I had used both in prior projects and find async-await a little more intuitive.

JavaScript's asynchrony is key to its usefulness for websites. In broad terms, asynchrony lets certain events in a program take place independently from the rest of the program. A request to another web location such as fetch takes time to complete, due to network speed and other factors. If the program underlying a web page had to stop and wait for a response every time, users would quickly get frustrated with the experience.

That's where async and await come into play. You can write a function just like you would normally, but specifying 'async' in front of the function declaration makes it return a promise - a special object that represents the response from an external source. Likewise, the keyword await before a function makes the function wait for a promise to arrive before it executes. It seems complicated but given its importance to modern web developing, it's worth the time to really understand how it all works.

My Project: Dad Jokes