Understand advanced functional programming concepts in JavaScript.
Example demonstrating closures and callback functions:
// Closure example: function retains access to outer scope variables
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
// Callback function example: executed after a delay
function greet(name, callback) {
console.log('Hello, ' + name + '!');
callback();
}
greet('Basha Ram', function() {
console.log('This is a callback function executing after greeting.');
});
This code demonstrates:
Closures: A closure occurs when a function retains access to its lexical scope even when executed outside of that scope. This allows functions to maintain private variables and state.
Callback Functions: These are functions passed as arguments to other functions, which are then invoked (called back) at a certain point in time, often after an asynchronous operation or event.
Q1: What does a closure allow a function to do?
Answer: B. Access variables from its lexical scope even after the outer function has returned
Q2: A callback function is:
Answer: B. A function passed as an argument to be executed later
Q3: Which of the following best describes a use case for closures?
Answer: A. Creating private variables
Q4: In the callback example, when is the callback function executed?
Answer: B. After greeting the user