Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
A callback is a function passed as an argument to another function, which then gets called (executed) at a later time. Think of it like leaving instructions for someone to follow after they finish their task!
You pass a function to another function, and it gets called when needed. The function you pass is the callback!
// Define a callback function
function sayHello() {
console.log('Hello!');
}
// Pass it to another function
function greet(callback) {
console.log('About to greet...');
callback(); // Call the callback!
console.log('Done greeting!');
}
greet(sayHello);
// Output:
// About to greet...
// Hello!
// Done greeting!You can define callbacks directly in the function call
Array methods like forEach, map, and filter take callbacks!
const numbers = [1, 2, 3, 4, 5];
// forEach - callback runs for each item
numbers.forEach(function(num) {
console.log(num * 2);
});
// Output: 2, 4, 6, 8, 10
// map - callback transforms each item
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled);
// Output: [2, 4, 6, 8, 10]
// filter - callback decides what to keep
const evens = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evens);
// Output: [2, 4]Modern syntax makes callbacks cleaner
Callbacks really shine when dealing with operations that take time - like timers, file reading, or network requests!
console.log('Start!');
setTimeout(function() {
console.log('This runs after 2 seconds');
}, 2000);
console.log('End!');
// Output:
// Start!
// End!
// (2 seconds later...)
// This runs after 2 seconds
// JavaScript doesn't wait!
// It continues and calls the callback laterTimers use callbacks to run code after a delay
Event listeners use callbacks to respond when users click, type, scroll, etc.
// Get a button element
const button = document.getElementById('myButton');
// Add event listener with callback
button.addEventListener('click', function() {
console.log('Button clicked!');
alert('You clicked me!');
});
// Multiple callbacks for same event
button.addEventListener('click', function() {
console.log('Another callback!');
});
// When user clicks:
// Output: Button clicked!
// Output: Another callback!
// Shows alert popupInteractive Example
const emailInput = document.getElementById('email');
const feedback = document.getElementById('feedback');
emailInput.addEventListener('input', function(event) {
const email = event.target.value;
if (email.includes('@') && email.includes('.')) {
feedback.textContent = '✅ Valid email format';
feedback.className = 'feedback valid';
} else if (email.includes('@')) {
feedback.textContent = '⚠️ Add domain (.com, .org, etc)';
feedback.className = 'feedback warning';
} else if (email.length > 0) {
feedback.textContent = '❌ Missing @ symbol';
feedback.className = 'feedback invalid';
} else {
feedback.textContent = '';
feedback.className = 'feedback';
}
});<div class="container">
<h2>Email Validation</h2>
<p>Type an email address below:</p>
<input
type="text"
id="email"
placeholder="Enter your email..."
/>
<div id="feedback" class="feedback"></div>
</div>The function calling your callback can pass data to it as arguments!
function processNumber(num, callback) {
console.log('Processing: ' + num);
const result = num * 2;
callback(result); // Pass result to callback!
}
processNumber(5, function(doubled) {
console.log('The doubled value is: ' + doubled);
});
// Output:
// Processing: 5
// The doubled value is: 10
// Array map passes 3 parameters!
[10, 20, 30].map(function(item, index, array) {
console.log('Item:', item);
console.log('Index:', index);
console.log('Array:', array);
return item * 2;
});Callbacks to track upload progress
When you nest callbacks inside callbacks inside callbacks... it becomes hard to read and maintain!
// DON'T DO THIS! ❌
getData(function(a) {
getMoreData(a, function(b) {
getMoreData(b, function(c) {
getMoreData(c, function(d) {
getMoreData(d, function(e) {
console.log('Finally done!');
});
});
});
});
});
// This is "Callback Hell" - hard to read!
// Solution: Use Promises or async/awaitCallbacks can create nested code quickly