Javascript Callback functions

What is a callback function? It’s quite confusing when I introduced this terminology as my way to learn the javascript developer. So I did some research and hope I could learn more about it.

MDN document explains it as “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.” To simplify this, the callback functions can be understood as the function called inside another function. But it’s more than that.

Before we getting to detail about it, let's talk about the functions in the javascript. Javascript, as a “function lover” programming language. There are 3 common use types of function.

Function Declaration,
Arrow Functions: anonymous, Function Expression: anonymous

Common types to write function in Javascript
Result in the console

which name is a built-in prototype of functions in javascript, it will refer to the function name, or the variable name assign by an anonymous function.

Javascript creates the first-class function which means that the functions are able to pass into another function as a name reference. This type of function makes our callback become easier.

Basic callback function

//Function Declaration
function add(callback){
return callback() + 10
};
add(function(){
return 1 + 2
})
//=> 13;
//function expression: function assign to a variable const minus = function(callback){
return callback() - 10
}
minus(() => {
return 10
})
//=> 0
//call by function name const number = () => 3; minus(number)
//=> -7

This is a way to pass an anonymous function into a function. Why does ES6 implement the arrow function, arrow function supports one line return. Javascript always looking for a way for the user to code easier and logically.

function(){return 1+2};//will return 3() => 1+2; //will return the exact same as previous code.

Helpful callback functions will include,

Methods for arrays: forEach, map, filter, find, every, findIndex … Check MDN for more methods for the array.

Methods in fetch: .then()

More callback function

Look at the basic callback functions above function calls a function is cool and convenient. However, there is a super useful syntax for the callback of Javascript.

const fun = (json) => console.log(json);fetch('URL')
.then(resp => resp.json())
.then(fun)

After running this code in the console, it will display the json. Why?

Compare to some other programming languages, javascript functions can take any arguments, it will not issue an error of the wrong number of arguments, and it’s not an error.

That goes, inside the callback function, javascript will take any return from the parent functions and pass it in as its own argument by passing it as a function.

To be more specific second .then() receives a json response. We initialize the funto take a (json) argument. So the json response will be the (json) to pass into funsince fun is a callback function in the .then() .

Now if you are still confusing, let’s make another common example: map. You can run this code in the console to see the result.

  1. let's say I have an array of numbers
const numbers = [1,2,3,4,5,6,7,8,9];

2. create a callback function we want to interact with forEach.

const tripling = (number) => number * 3;

3. use the map function in a simple syntax

numbers.map(tripling);

When the map function returns each number in the numbers such 1, the tripling function will take 1 as argument return 3, then take in 2, tripling will be tripling(2) and returns 6 then map will execute the later codes in the map function push the results to the new array, once all item in numbers mapped it returns the new array.

It is the same as

numbers.map(returnValue => tripling(returnValue));

Deeper into callback syntax

After several attempts, I was wonder if this easy syntax works with multiple params. As a result, with some researches, it works. But should be careful with the values of your function returns, it might hit make your program hit bugs: If the arguments are wrong, and leading to confusing bugs.

Javascript is good

Javascript makes code simpler and simpler for the developers to write it. It’s getting easier to code as time goes by because they want the developers to code with less typing and easier.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What is NodeJS.?

A better practice: Mixing Gin with Next.JS, and NextAuth on the side

Re-visit JavaScript Iterations (using Iterators and Generators)

AWS Amplify Release, GraphQL, and Recent Curated Links

Disabling scroll chaining

Creating a Web Application in Angular 10, Web API & SQL Server from Scratch — Part 1

hygen the sh*t out of your React application — Part 1

Mapping out the React App

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Eddy Gao

Eddy Gao

More from Medium

Scope in JavaScript

Hoisting in Javascript

How to build Micro Frontend Based on Angular?

Hoisting in javascript | Codementor