As newbie developer, one of the most confusing functions I had to get a grasp on was callback functions.
Like, seriously, confusing. So, let's break them down into plain English.
DEFINITION
According to the G.O.A.T., MDN, Callback Functions are:
"A function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action."
Huh?
Let's look an example.
EXAMPLE IN ACTION
As our labs got more complex, I was calling callback functions without even knowing it. Honestly, to me, this is the best way to learn them. Let's take a look at a lab and see what's happening here.
First, all of my functions are called as a promise in my .then with my JSON data.
The first function, firstMovie, is calling the data array of movies (movieData) that should be put onto my website as an object. All of these variables are defined, an event listener is called for a separate button (we don't need to worry about that).
The second function, createImage, is telling the movieData to display an image associated with the each movie, and then for that to be displayed as a navigation bar.
But hey, there's firstMovie again! What's up with that?
createImage isn't doing anything too exciting by itself without the help of firstMovie - it's just displaying an image. We can use the power of the previous function, firstMovie to help it do more!
By calling firstMovie inside of createImage, we're able to create an event listener that tells this new image we created through createImage to lean on the power of firstMovie in displaying details of all of the movies. It's doing that by on the click, activating exactly what firstMovie does - iterate through all of the JSON data for the movies and display it with the associated navigation image!
fetch("http://localhost:3000/movies")
.then(res => res.json())
.then(movieData => {
firstMovie(movieData[0]);
createImage(movieData);
})
function firstMovie(movieData) {
title.textContent = movieData.title
description.textContent = movieData.description
year.textContent = movieData.release_year
pic.src = movieData.image
watchedBtn.addEventListener('click', (e) => {
movieData.watched = !movieData.watched;
watchedBtn.textContent = movieData.watched ? "Watched" : "Unwatched";
});
}
function createImage(movieData){
movieData.forEach((movie) => {
let img = document.createElement("img");
img.src = movie.image
insertImage.append(img)
img.addEventListener('click', (e) => {
firstMovie(movie)
});
})
}
YOU GOT THIS.
Still confused about callback functions? Please enjoy this incredible YouTube video by bersling, which has the most delightfully personified functions that will have you understanding callback functions in no time (and wanting to eat bread).
*Image Sources: Made by ME!
*
Top comments (2)
Nice job! :)
Terrific blog, Rachel! π«