Skip to content
Newsletter

What is a Callback?

A callback is a function that is passed as an argument to another function to be executed after an asynchronous operation has been completed. 

Callbacks allow developers to write asynchronous, non-blocking code in a way that appears synchronous and enables proper code execution sequencing. 

Understanding callbacks is crucial for app developers as apps need to handle many asynchronous events and operations like user interactions, loading data, API requests, UI animations, and more.

Mastering callbacks helps developers write performant apps that remain responsive instead of blocking the UI when performing long operations.

How Do Callbacks Work?

With callbacks, you pass a function as a parameter to another function that will execute the callback function at the appropriate time.

A simple example is the setTimeout function:

“js function myCallback() {console.log(‘Callback executed!’);} setTimeout(myCallback, 1000);”

Here myCallback is passed as a parameter and setTimeout will execute it after 1 second.

The pattern also applies to event listener functions you pass to handle click events, data loading callbacks, etc.

Callbacks enable asynchronous logic in JavaScript and other languages to be written in a synchronous style. The callback handles the async part separately from the main code.

Key Benefits of Using Callbacks in Apps

There are several reasons callbacks are indispensable in app development:

Examples of Callbacks in Apps

Some common use cases of callbacks in apps include:

Problems with Nested Callbacks

While callbacks enable asynchronous logic in JavaScript, deeply nested callbacks can make code hard to understand, maintain, and debug. This is known as “callback hell”.

Simple callbacks are fine, but complex callback hierarchies with poor separation of concerns can create a pyramid of doom style code that is difficult to reason about. Engineers should aim to break callbacks into separate functions and use principles like separation of concerns.

For more complex async logic, promises or async/await provide a better abstraction over callbacks. They allow writing async code that reads more clearly in a synchronous, procedural style. Libraries like RxJS also help manage callback complexity for reactive apps.

Best Practices When Working with Callbacks

Follow these tips for a clean callback code:

F.A.Q

Q1: What is the purpose for a callback?

A1. A callback allows asynchronous code execution.

Q2: Are callbacks good or bad? 

A2. Callbacks are good as they enable non-blocking async logic but can create complex code if overused.

Q3: What is Callback in simple terms?

A3. A callback is a function passed as an argument to be executed later. 

Q4: What to expect at callbacks? 

A5. At acting callbacks, expect to perform short scenes or monologues for the casting directors.

More from Glossary