The Essential Callback Function

Jason Kuffler
2 min readAug 3, 2021

--

I’m Jason Kuffler. Pronounced Jay-Sun Koo-Fler. My friends call me Kuffler or whatever creative spin you wanna put on that.

Today I’m sharing my first ever tech blog! As a new student at Flatiron School I’ll be blogging some of my progress through the course.

When learning JS with no modern programming background you may feel a bit overwhelmed by the infinite pool that is JS. My goal here is to help create a lucid understanding of the oh-so-powerful and absolutely necessary:

CALL BACK FUNCTION

The function declaration will resemble something like:

function example(parameter){
//code
}

Parameter here is creating a variable within the scope of the function meaning the parameter is usable inside the function.

When you’re declaring an anonymous function like so . . .

const example = function () {
//code
}
example();//called the example function

. . . the anonymous function is set to a variable which allows us to actually call/invoke our anonymous function. Not always necessary but in this case it’s certainly easy.

The callback function is part of another function. Which part?! The callback is called as an argument to another function. This concept in action will become a very powerful ally across a wide cross-section of uses in your development work. Take a look!

function sayHey(name) {
alert('Hey' + name);
}

function handleGreeting(callback) {
const name = prompt('Please enter your name.');
callback(name);
}

handleGreeting(sayHey);

G’head and look at that again. The parameter for handleGreeting() could be anything we choose. It will hold the place for an argument which (in this case) is our callback function sayHey. I didn’t fully comprehend this concept for a few intense days of nearly non-stop coding. When the light came on though — WOOOO-WEEEEEE!

What is happening?

We’ve set one function sayHey() to handle our alert with a greeting based on what’s typed by the user. The handleGreeting() function is declared with a callback parameter. Important to do so or else you can not add arguments when you call the function. Finally we call/invoke the handleGreeting() function and pass the separate function sayHey (this time without the parentheses — more like a plain ol’ variable) as it’s sole argument. As usual: JS is very accommodating.

I highly recommend toying around with callbacks in order to remain cognizant as you delve into advanced JS! Start small. When you’re feeling ready, then go wild as you adapt to this very powerful tool!

--

--

Jason Kuffler

Creative. Researcher. Coder. Rad Dad. Sharing easy-to-follow progress covering my tech ed