What is a callback function in JavaScript?
A
A function that is called after a delay B
A function passed as an argument to another function C
A function that calls itself D
A function used only in loops
Analysis & Theory
A callback is a function passed into another function to be executed later.
What will this output?
```js
function greet(name, callback) {
return callback(name);
}
function sayHello(n) {
return 'Hello, ' + n;
}
console.log(greet('Alice', sayHello));
```
A
`Hello, Alice` B
`Alice, Hello` C
`undefined` D
`Error`
Analysis & Theory
`sayHello` is passed as a callback to `greet`, and it returns `'Hello, Alice'`.
Which of the following correctly uses a callback?
A
`function add(a, b) { return a + b; }` B
`setTimeout(logMessage(), 1000);` C
`setTimeout(function() { console.log('Hi'); }, 1000);` D
`console.log('Callback')`
Analysis & Theory
Passing an anonymous function to `setTimeout` is a valid use of a callback.
Why are callbacks used in JavaScript?
A
To block code execution B
To handle asynchronous operations C
To slow down the program D
To load CSS
Analysis & Theory
Callbacks are often used to handle results of asynchronous operations like API calls or timers.
What is the output?
```js
function process(num, cb) {
return cb(num);
}
console.log(process(5, function(n) { return n * n; }));
```
A
`5` B
`10` C
`25` D
`undefined`
Analysis & Theory
`cb(5)` returns `5 * 5 = 25`.
What is true about named vs anonymous callback functions?
A
Only anonymous callbacks work B
Only named functions are valid callbacks C
Both can be used as callbacks D
Only arrow functions are allowed
Analysis & Theory
Both named and anonymous functions can be used as callbacks.
What is the output?
```js
function test(cb) {
cb();
}
test(() => console.log('Done'));
```
A
`Done` B
`test` C
`undefined` D
`Error`
Analysis & Theory
An arrow function is passed and executed, logging `'Done'`.
Which of these is a common problem with callbacks?
A
Callback typing B
Callback pyramid (callback hell) C
Callback misrouting D
Callback encoding
Analysis & Theory
Nested callbacks can lead to difficult-to-read code, known as callback hell.
How can you avoid callback hell?
A
Use nested callbacks only B
Use long function names C
Use Promises or async/await D
Avoid functions
Analysis & Theory
Promises and async/await help manage asynchronous flow more cleanly than nested callbacks.
Which is a real-world use of callbacks?
A
`document.getElementById()` B
`parseInt()` C
`setTimeout(() => console.log('Hi'), 1000)` D
`alert()`
Analysis & Theory
`setTimeout` takes a callback function that runs after a delay.