Dive deep into closures, lexical scope, higher-order functions, callbacks, and IIFE to enhance your JavaScript skills and write optimized, maintainable, and powerful code.
Closures and Lexical Scope (8 MCQs)
What is a closure in JavaScript?
A) A function bundled with its lexical environment
B) A method to close an open file
C) A block of code executed immediately
D) A syntax for declaring variables
Which of the following is a key feature of closures?
A) They can modify variables declared in their outer scope
B) They do not allow variable sharing
C) They execute outside their lexical environment
D) They can only be called once
What determines the lexical scope of a function in JavaScript?
A) The function’s arguments
B) Where the function is defined in the code
C) The function’s name
D) The browser’s JavaScript engine
How can closures be used in JavaScript?
A) To prevent memory leaks
B) To create private variables
C) To execute code asynchronously
D) To modify the global object
Which of the following scenarios demonstrates a closure?
A) A function that calls another function inside its body
B) A function that returns another function and uses variables from the outer scope
C) A function that has no parameters
D) A function that calls itself recursively
What happens to the variables used in a closure after the outer function has executed?
A) They are deleted immediately
B) They remain accessible through the closure
C) They are moved to the global scope
D) They are inaccessible
Which of the following best describes lexical scope?
A) Scope determined at runtime based on the call stack
B) Scope determined during the declaration phase
C) Scope that can be modified dynamically
D) Scope limited to local variables only
What is the output of this code?javascriptCopy codefunction outer() { let count = 0; return function inner() { count++; return count; }; } const counter = outer(); console.log(counter()); // ? console.log(counter()); // ?
A) 1, 2
B) 0, 1
C) 2, 2
D) Error
Higher-Order Functions (8 MCQs)
What is a higher-order function in JavaScript?
A) A function that returns an object
B) A function that accepts or returns another function
C) A function with nested loops
D) A function declared with the async keyword
Which of the following is an example of a higher-order function?
A) A function that calculates the square root
B) Array.map()
C) Math.pow()
D) A function that declares a variable
Why are higher-order functions important in JavaScript?
A) They enhance performance
B) They reduce code redundancy
C) They enable functional programming techniques
D) All of the above
Which of the following functions is not considered a higher-order function?
A) Array.forEach()
B) Array.reduce()
C) console.log()
D) Array.filter()
How do higher-order functions achieve reusability?
A) By creating multiple objects
B) By abstracting common logic into reusable components