Book Image

Mastering JavaScript Promises

Book Image

Mastering JavaScript Promises

Overview of this book

Table of Contents (16 chapters)
Mastering JavaScript Promises
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

The mechanism of a callback function in JavaScript


The question here is, how on earth does a callback function work?

As we know that functions are like first class objects in JS, we can pass them around in a similar way to variables and return them as functions and use them in other functions.

When we pass a callback function as arguments to another function, we are only passing the function definition. We aren't executing functions in parameters. We are also not passing the function with the trailing pair of executing parenthesis (), as we would when we are executing a function.

Since the containing function has the callback function in its parameter as a function definition, it can execute the callback at any time.

It is important to note that the callback function is not executed immediately. It is "called back" and can still be accessed later via the arguments object by the containing function.

Basic rules to implement callbacks

There are some basic rules that you need to keep in mind while...