Disclaimer: I’ve never had to create a JavaScript callback function as professional web developer. It is unlikely that you will ever have to create a function that takes a callback either, especially since there are alternatives to callbacks; however, you’ll probably run into a one of these when using a package built by someone else.
Visit Replit.com to play around with this code: https://replit.com/@paircoder/Callbacks#script.js.
export function removeSpamComments(comments, nextAction) { comments.pop(); nextAction(comments); }
import { removeSpamComments } from './remove-spam-comments.js'; function displayComments (comments) { // code to display comments after removing spam console.log('clean comments', comments); } let comments = ['Great post!', 'Wow!', 'Visit stealmyinfo.com for great resources!']; removeSpamComments(comments, displayComments); function doSomethingCompletelyDifferent () { // code to do something completely unrelated to comments console.log('I am doing something completely unrelated to comments'); } removeSpamComments(comments, doSomethingCompletelyDifferent);
Code Dissection
export function removeSpamComments(comments, nextAction) {
The removeSpamComments is located in a different file. The removeSpamComments function removes spam comments and then lets you do something with the clean comments. It receives two parameters. The first parameter should be an array of comments. The second parameter should be a function. The second parameter is the callback function.
comments.pop();
This is just used for illustration and is actually a terrible way to remove spam comments.
nextAction(comments);
When the function is done removing the spam comments, it calls the callback function and passes the clean comments to it.
function displayComments (comments) { … }
We create a function to pass to the removeSpamComments function. We give it one parameter because we know that the removeSpamComments function will pass the clean comments to the callback function.
removeSpamComments(comments, displayComments);
We call the function to remove the spam comments, and we give it our function as the second parameter to display the comments.
doSomethingCompletelyDifferent
Instead of displaying comments, we decide to do something completely different.