Module 11: JavaScript Interview Questions and Answers
Functions, Scope, and Closure Interview Questions
Prepare for questions about hoisting, closures, arrow functions, and this.
1. What is a function declaration?#
Answer: It defines a named function using function name() { ... }. Function declarations are initialized during scope setup, so they can generally be called before their declaration appears in the source.
2. What is an arrow function?#
Answer: An arrow function is a concise function expression using =>. It does not have its own this or arguments, and it cannot be called as a constructor with new.
3. What is scope?#
Answer: Scope determines where a binding can be accessed. JavaScript commonly uses global, function, and block scopes. let and const are block-scoped, while var is function-scoped.
4. What is hoisting?#
Answer: Hoisting is a common shorthand for the way declarations are processed when a scope is created. It does not literally move source code. Function declarations are initialized; var is initialized to undefined; let and const are inaccessible during their temporal dead zone.
5. What is a closure?#
Answer: A closure is a function together with access to its surrounding lexical environment. It allows a function to retain state or use outer variables after the outer function has returned.
6. Give a practical use of closures.#
Answer: Closures are used in callbacks, event handlers, function factories, and private state patterns. A counter factory can return a function that retains a count variable between calls.
7. How does this work?#
Answer: For regular functions, this is determined by the call form. In a method call, it usually refers to the receiver object. Arrow functions capture this lexically from their surrounding context.
8. What are call, apply, and bind?#
Answer: call immediately invokes a function with a chosen this and positional arguments. apply invokes it with arguments supplied as an array-like value. bind returns a new function with a preset receiver and optional arguments.
9. What is a higher-order function?#
Answer: A higher-order function accepts a function as an argument, returns a function, or both. Array methods such as map and filter commonly receive callbacks.
10. What is a pure function?#
Answer: A pure function returns the same output for the same inputs and has no observable side effects. Pure functions are easier to test and reason about, although real applications also need controlled side effects such as network requests.
11. What is the difference between parameters and arguments?#
Answer: Parameters are names in the function definition; arguments are values passed at the call site.
12. What is an IIFE?#
Answer: An Immediately Invoked Function Expression is a function expression invoked right after it is created. It was commonly used to create a local scope before ES modules became widespread. It still has uses, but modern modules often make it unnecessary.