The event loop is a mechanism that allows JavaScript to handle asynchronous operations (like I/O,
timers, etc.) without blocking the main thread. It continuously checks the call stack for any code to
execute and moves tasks from the callback queue to the call stack when the stack is empty.
8. What are closures in JavaScript?
A closure is a function that retains access to its lexical scope (the scope in which it was created)
even after that scope has finished execution. Closures allow functions to access variables from an
outer function after the outer function has returned.
function outer() {
let x = 10;
return function inner() {
console.log(x);
const closureFunc = outer();
closureFunc(); // prints 10
Output
10
9. Explain the concept of this in JavaScript.
In JavaScript, the this keyword refers to the context in which a function is called. It is used to refer to
the object that is executing the current piece of code.
The value of this can change depending on how the function is called. Here are the different
scenarios where this behaves differently:
Global context: In non-strict mode, this refers to the global object (window in browsers).
Object method: this refers to the object the method belongs to.
Constructor function: this refers to the instance of the object being created.
Arrow functions: In arrow functions, this is lexically bound to the surrounding context.
10. What is a callback function in JavaScript?
A callback function in JavaScript is a function that is passed as an argument to another function and
is executed after the completion of that function. Callback functions are primarily used for handling
asynchronous operations, such as API requests or timeouts, ensuring that certain code runs only
after a specific task is completed.
function greet(name, callback) {
console.log("Hello " + name);
callback();
function sayGoodbye() {
console.log("Goodbye!");
greet("Anjali", sayGoodbye);
Output
Hello Anjali
Goodbye!