Callback functions in JavaScript

Yahya Gok
2 min readAug 29, 2021

A callback function is 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.(1)

picture 1; let’s explain the callback function with an example. We have a function called mapping, this function maps through an array and do something with a callback variable that I passed in, callback variable could be anything also can do anything. This callback is go into be always function that we can invoke. We don’t invoke that function right away, we just reference it as callback, like we don’t type callback(), only callback as reference. We could say anything as name instead of callback, it could be something else. I gave this name because our topic is callback.

picture 1

picture 2; Now, let’s create a new array(which is brandNewArray with empty brackets) and add to this array, changedItem which is an variable that callback invoked in that given array’s item. Just want to remind you, callback is just a function that can be anything. Why we create new array ? , just to show how callback functions changes the given array’s item.

At the end of mapping function, we return brandNewArray to see how it changed.

picture 2

picture 3; in the below picture we created a new function addFive, this function adds +5 to given item. Also, this function will be used as callback function. Because, when we created mapping function, we give second argument as callback. When we console.log (mapping([1,2,3,4], addFive)), addFive is the second argument which means that it represents callback.

picture 3

The result will be [6,7,8,9],

References

--

--