Many native methods in JavaScript uses callback functions. When you first see the callback function usage, liek in example below, when it is passed as another method’s argument, than it may look strange for you. You can think how the method can me an argument of a function? But this is quite simple, when we check in details our examples of JavaScript callback function with parameters below.
Table of Contents
JS callback with parameters
Let’s consider e.g. Array map
method. You can have a variable containing array like: const numbers = [9, 8, 7, 6, 5, 4]
and you can change all it’s elements by running a map
method with a js callback function with parameters (here: item
) which will do the same operation on every element in array, like e.g. multiplying it by 2:
const numbers = [9, 8, 7, 6, 5, 4]; const results = numbers.map(function (item) { return item * 2; });
So in example of JavaScript code above, the callback function with parameter item
is:
function (item) { return item * 2; }
Passed as argument into Array map
method. Of course, remember that you can pass a JavaScript callback function with ES2015 syntax, so with arrow function in much shorter way (item) => item * 2
and then map
method callback function with parameter item
will look like below:
numbers.map((item) => item * 2);
JavaScript create callback function
You can create a JavaScript callback function in your normal JavaScript code on your own. In some cases this is very useful trick, which allows you to do custom operation inside another function. Check my another article with WAIT function in JavaScript where I’m using callback function in practice.
But lets go step by step and let’s create own JavaScript callback function in example below. It’s very easy! Check out code below:
function sumNumbersWithExtension (a, b, callback) { var res = a + b; if(typeof callback === "function") { res = callback(res); } return res; } var res1 = sumNumbersWithExtension(1, 2); var res2 = sumNumbersWithExtension(1, 2, (internalVal) => { console.log(internalVal); return internalVal * 10; }); console.log("res1: ", res1); // res1: 3 console.log("res2: ", res2); // res2: 30
So as you can see, by creating a callback in JavaScript function inside another function you can have “access” to internal values of parent function in callback function. You can do another operations in parent function, so it gives you a huge flexibility for your code.
In example of JavaScript callback function above:
- first, we assigned to the variable “res1” the same function without creating callback function, and it returned “3”
- in second example, we created JavaScript a callback function which modified the sum of
a + b
like internal function inside parent one.
Isn’t it great? 🙂 Now you will be able to create a callback functions inside your JavaScript code and make it more flexible. I hope that my example make it more clear to you how to use it.