JS Callbacks 🎯

beginner
19 min

JS Callbacks 🎯

Welcome to our deep dive into JavaScript Callbacks! In this comprehensive guide, we'll explore this powerful feature, perfect for beginners and intermediates.

What are Callbacks? 📝

Callbacks are functions passed as arguments to other functions, to be executed later. They help manage asynchronous operations, allowing your code to proceed while waiting for a result.

Why Callbacks? 💡

Callbacks enable us to write more modular and flexible code. They help in handling events, fetching data from APIs, and much more. They allow your code to be non-blocking, making it more efficient and responsive.

Understanding Callbacks 📝

Function Expressions

First, let's cover function expressions, which are fundamental to understanding callbacks.

javascript
function greet(name) { console.log(`Hello, ${name}!`); } greet('Alice'); // Output: Hello, Alice!

Here, greet is a function that takes an argument name and logs a greeting message.

Callback Functions

Now, let's create a callback function:

javascript
function greetCallback(callback) { const name = 'Alice'; callback(name); // We pass the greet function as a callback here } function greet(name) { console.log(`Hello, ${name}!`); } greetCallback(greet); // Output: Hello, Alice!

In this example, greetCallback is a function that takes a callback function as an argument and executes it with an argument name. Here, greet is our callback function.

Real-World Callbacks 💡

Callbacks play a crucial role in handling events and AJAX requests. Here's an example of a callback for handling a click event:

javascript
function handleClick(callback) { document.getElementById('myButton').addEventListener('click', function() { callback(); }); } function showAlert() { alert('Button clicked!'); } handleClick(showAlert); // Adds event listener to the button and calls showAlert when clicked

Advanced Callbacks 💡

Error-First Callbacks

Error-first callbacks are a convention for returning errors and results in asynchronous functions. They put the error (if any) first, followed by the result.

javascript
function getUser(callback) { setTimeout(function() { const user = { name: 'John Doe' }; callback(null, user); // No error, returns the user object }, 2000); } getUser(function(error, user) { if (error) { console.error('Error:', error); } else { console.log('User:', user); } });

Practice Time 🎯

Quick Quiz
Question 1 of 1

Which of the following is a callback function?

Quick Quiz
Question 1 of 1

What is the purpose of error-first callbacks?