👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
You’ve probably seen that some snippets use the word " callback " in a function. Callbacks are a special type of function that is passed inside another function.
Callbacks are often used in event handlers to execute a block of code. In this guide, we’ll talk about what callbacks are and how they work. We’ll look at an example callback function to help you learn how to use them in your code.
What is a callback function?
A callback function is a function passed as a parameter to another function.
Callback functions are executed inside the function in which they are declared. When executing a function, its callback function, if specified, will be executed. When executed, the callback function returns a response to the main function.
Callback functions work because in JavaScript each function is an object. This means that we can work with them like any other object. We can assign functions to variables or pass them as arguments, just as we would with any other value.
Let’s use a simple example to show how callbacks work. We are going to create a function that prints the name of a user for a video game on the console, followed by the type of character. Let’s start by declaring a function:
This is an anonymous JavaScript function that contains a callback. Anonymous functions are unnamed functions. They usually appear inside other functions, as in the example above.
This callback is the second parameter of our code. When this function is performed, our player’s name is printed on the console. Then the contents of our callback () function are executed.