This program simulates fetching data with a 2-second delay. After data is ready, the callback runs and prints the data.
Javascript
function fetchData(callback) {
console.log('Start fetching data...');
setTimeout(() => {
console.log('Data fetched');
callback('Here is your data');
}, 2000);
}
fetchData(function(data) {
console.log('Callback received:', data);
});
OutputSuccess
Important Notes
Callbacks help manage tasks that take time, like loading data.
Without callbacks, code might run too early before tasks finish.
Too many callbacks can make code hard to read, called "callback hell".
Summary
Callbacks are functions passed to other functions to run later.
They help wait for tasks to finish before continuing.
Use callbacks for events, timers, and asynchronous work.
Practice
(1/5)
1. What is a callback function in JavaScript?
easy
A. A function that runs immediately without waiting
B. A function passed as an argument to another function to be called later
C. A function that only runs once when the program starts
D. A function that cannot be passed to other functions
Solution
Step 1: Understand the role of callbacks
A callback is a function given to another function to run after some work is done.
Step 2: Match the definition
A function passed as an argument to another function to be called later correctly describes this behavior as a function passed as an argument to be called later.
Final Answer:
A function passed as an argument to another function to be called later -> Option B
Quick Check:
Callback = function passed to run later [OK]
Hint: Callbacks are functions given to run after another function finishes [OK]
Common Mistakes:
Thinking callbacks run immediately
Confusing callbacks with event listeners only
Believing callbacks cannot be passed as arguments
2. Which of the following is the correct syntax to use a callback in JavaScript?
easy
A. function greet(callback) { callback }
B. function greet() { callback(); }
C. function greet(callback) { callback; }
D. function greet(callback) { callback(); }
Solution
Step 1: Check how the callback is called
The callback function must be called with parentheses: callback()
Step 2: Identify correct syntax
function greet(callback) { callback(); } correctly defines a function that takes a callback and calls it with callback()
Final Answer:
function greet(callback) { callback(); } -> Option D
Quick Check:
Call callback with parentheses to execute [OK]
Hint: Call callbacks with parentheses to run them [OK]