JavaScript Functions Advanced Interview Questions and Answers
Explore callbacks, higher-order functions, closures, recursion, and other patterns built from functions.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
Theoretical JavaScript Interview Questions
First-class functions means functions in JavaScript are treated like any other value. You can store them in variables, pass them as arguments, and return them from other functions. This is a big deal - it's not something every language supports.
This enables powerful patterns: callbacks (passing
functions to handle events), higher-order functions
(functions that take or return other functions), and
array methods like .map() and
.filter(). It's the foundation of
functional programming in JavaScript and makes your
code more composable and reusable.
Functions in JavaScript are first-class values - you can store them in variables, pass them as arguments, return them from other functions, and put them in arrays or objects, just like any other value. This is what makes patterns like callbacks, higher-order functions, and closures possible. It's a fundamental feature that shapes how JavaScript code is written.
const greet = function(name) { return "Hello, " + name; };
console.log(greet("Alice")); // Hello, Alice
function run(fn) { return fn("Bob"); }
console.log(run(greet)); // Hello, Bob
A higher-order function either takes a function as an argument or returns a function. The built-in array methods map, filter, and reduce are higher-order functions you'll use constantly. Understanding them is key to writing clean, reusable JavaScript.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
function multiplier(factor) {
return n => n * factor;
}
const triple = multiplier(3);
console.log(triple(5)); // 15
A callback is just a function you pass to another function so it can call it later. Before Promises and async/await, callbacks were how all async work was done - setTimeout, event listeners, and Node's fs.readFile all use them. They're still everywhere, so understanding them is essential. The downside is deeply nested callbacks ("callback hell"), which is why Promises were introduced.
function fetchData(callback) {
setTimeout(() => {
callback("Data loaded");
}, 1000);
}
fetchData(result => console.log(result)); // Data loaded (after 1s)
A closure is a function bundled with its surrounding lexical environment - it remembers the variables from the scope where it was created, even after that scope has gone. This is how you get private state in JavaScript. Every function in JS is technically a closure, but the term is usually used when you return a function from another function and the inner function keeps access to the outer variables.
function makeCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Currying transforms a multi-argument function into a chain of single-argument functions, enabling partial application - pre-filling some arguments to get back a specialized function. It's a functional programming concept used heavily in libraries like Lodash and Ramda. You'll encounter it more in interviews and functional-style code than in typical app development.
// Normal function
function add(a, b) { return a + b; }
// Curried version
function curriedAdd(a) {
return function(b) {
return a + b;
};
}
const addFive = curriedAdd(5);
console.log(addFive(3)); // 8
console.log(addFive(10)); // 15
Recursion is when a function calls itself to solve a smaller version of the same problem. Always define a base case - a condition where the function returns without calling itself - otherwise you'll hit a stack overflow. It's natural for tree/graph traversal, nested data structures, and divide-and-conquer algorithms. For large inputs, be aware JavaScript has a finite call stack, so deep recursion can crash - consider iteration if depth is unbounded.
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive call
}
console.log(factorial(5)); // 120
// 5 * 4 * 3 * 2 * 1 = 120
A wrapper can keep a `called` flag in its own lexical scope. Set the flag before invoking the callback; later calls can return without invoking it again. Each wrapper gets independent state.
Closures are useful for two main things. They let you create private variables that nothing outside the function can access or modify. They also allow functions to hold onto some state between calls, like a counter that keeps incrementing or a value that gets computed only once and remembered.
A common use case is creating a counter or a function factory where each function gets its own private piece of state. Another very common use is the module pattern, where you expose only specific functions and keep everything else private.
function makeMultiplier(multiplier) {
return function (num) {
return num * multiplier;
};
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
When you use var inside a loop and create a function for each iteration, all those functions share the same variable. By the time any function runs, the loop is already done, so they all see the final value. Using let fixes this because let creates a new binding for each loop iteration.
// Problem with var
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// prints: 3, 3, 3
// Fixed with let
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// prints: 0, 1, 2
Closures keep the outer function's variables alive in memory as long as the inner function exists. This is intentional and useful, but it can cause memory issues if you are not careful. If you hold onto a closure that references a large object and you never let go of that closure, the large object stays in memory longer than needed. Once you no longer need the closure, set the reference to null so the garbage collector can clean it up.
Technically, every function in JavaScript is a closure because every function has access to its own scope plus the scopes around it. That said, the term "closure" is normally used when a function is still using variables from an outer function that has already finished running. If a function only works with its own arguments and local variables, there is no meaningful closure in play, even though the scope chain still exists. The interesting part of closures is when that outer scope stays alive because of a function holding onto it.
A pure function gives the same output for the same inputs and does not change anything outside itself. It does not update shared state, read the current time, or produce other side effects.
A trampoline changes recursive steps into functions that describe the next step, then runs those steps in a loop. This avoids growing the JavaScript call stack for every recursive step, though the extra machinery can make simple code harder to read.