JavaScript Functions Interview Questions and Answers
Review function declarations, expressions, parameters, return values, and the differences between function forms.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
- What is a function declaration and how does it differ from a function expression?
- What is an arrow function and how does it differ from a regular function?
- What is an IIFE (Immediately Invoked Function Expression)?
- What is a function in JavaScript?
- What is "this" in JavaScript?
- What is the arguments object in JavaScript?
- What is functional programming in JavaScript?
Theoretical JavaScript Interview Questions
document.write() injects content straight into the HTML document as it loads. Here's the big gotcha: if you call it after the page finishes loading, it wipes out everything on the page and replaces it with your content. That alone makes it dangerous for real apps. It also blocks HTML parsing, can cause race conditions with async scripts, and doesn't play well with modern rendering. You might see it in old tutorials or quick throwaway demos, but in production code, use DOM methods like createElement() or textContent instead.
Fall-through happens when a switch case has no break, so execution continues into the next case.
Always add break after each case unless fall-through is intentional, and add a comment when it is.
Unintended fall-throughs are a common source of bugs.
A function declaration uses the function keyword as a statement and is fully hoisted - you can call it before the line where it's defined. A function expression assigns a function to a variable and isn't hoisted, so it must be defined before you call it. In modern code, declarations are common for named top-level functions, while arrow function expressions are the norm for short utilities and callbacks.
// Function Declaration - hoisted
console.log(square(3)); // 9
function square(n) { return n * n; }
// Function Expression - NOT hoisted
// console.log(cube(3)); // TypeError
const cube = function(n) { return n * n * n; };
console.log(cube(3)); // 27
Arrow functions are a shorter syntax introduced in ES6, but the most important difference is how this works - they don't have their own this, they inherit it from the surrounding scope. That makes them great for callbacks inside class methods or event handlers. Don't use arrow functions as object methods or constructors - the this binding will surprise you.
- No own
this: inheritsthisfrom the enclosing scope. - No
argumentsobject. - Cannot be used as a constructor (no
new). - Supports implicit return when body has no curly braces.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
const obj = {
value: 10,
regular: function() { return this.value; }, // 10
arrow: () => this // refers to outer 'this', not obj
};
The arguments object is an array-like object available inside regular functions that contains all the values passed in, regardless of how many parameters were defined. It's array-like but not a real array - so you can't call .map() on it directly. In modern JS, use rest parameters (...args) instead - they give you an actual array and also work inside arrow functions.
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3, 4)); // 10
In modern JavaScript, it is recommended to use rest parameters (...args) instead, which gives you a real array that you can immediately call .map(), .filter(), etc. on.
Default parameters let you define a fallback value used when a caller doesn't pass that argument (or passes undefined explicitly). One thing to watch: defaults are evaluated fresh each call - if you use an object as a default, you get a new instance each time, which is actually better behavior than Python's mutable default gotcha.
function greet(name = "Guest") {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet()); // Hello, Guest!
Default values are evaluated at call time, not at function definition time. They can also reference other parameters defined before them in the parameter list.
Primitives (numbers, strings, booleans) are passed by value - the function gets a copy, so changes inside don't affect the original. Objects and arrays are passed by reference - the function gets a reference to the same object, so mutating it affects the caller's data. The gotcha: reassigning the parameter itself doesn't affect the original, but mutating a property does.
// Primitive - pass by value
function addTen(n) { n += 10; }
let x = 5;
addTen(x);
console.log(x); // 5 (unchanged)
// Object - pass by reference
function rename(person) { person.name = "Bob"; }
const user = { name: "Alice" };
rename(user);
console.log(user.name); // Bob (changed)
An IIFE is a function that runs immediately after it's defined. Before ES modules and block scoping with let/const, IIFEs were the standard way to create a private scope and avoid polluting the global namespace. You still see them in legacy codebases and some build tool output. In modern code, modules handle encapsulation so IIFEs are rarely needed.
(function() {
const message = "I run immediately!";
console.log(message);
})();
// Arrow function IIFE
(() => {
console.log("Arrow IIFE");
})();
Memoization caches the result of a function call so if you call it again with the same arguments, you get the cached result instead of recomputing. It's a memory-for-speed trade-off - use it for pure functions with expensive computations and repeated identical inputs. React's useMemo and useCallback are built-in examples. It's most useful when the same inputs occur often; otherwise the cache overhead isn't worth it.
All three let you explicitly set the value of this when calling a function. call and apply invoke the function immediately - the only difference is call takes individual arguments while apply takes them as an array. bind returns a new function with this permanently set, without calling it - useful for event handlers and passing methods as callbacks. In modern code, arrow functions often replace the need for bind since they capture this lexically.
- call(): invokes the function immediately, arguments passed one by one.
- apply(): invokes the function immediately, arguments passed as an array.
- bind(): returns a new function with
thisbound, does not call it immediately.
function greet(city, country) {
return this.name + " from " + city + ", " + country;
}
const person = { name: "Alice" };
console.log(greet.call(person, "Paris", "France"));
console.log(greet.apply(person, ["Paris", "France"]));
const boundGreet = greet.bind(person, "Paris", "France");
console.log(boundGreet()); // called later
A function is a reusable, named block of code. The important thing in JavaScript is that functions are first-class - you can assign them to variables, pass them as arguments, and return them from other functions, just like any other value. This is the foundation for callbacks, closures, higher-order functions, and most of the patterns modern JavaScript is built on.
Functional programming centers on three ideas: pure functions (no side effects, same input always returns same output), immutability (don't mutate data, create new copies), and higher-order functions (functions that take or return other functions). In practice this means favoring map, filter, and reduce over loops and mutations. Pure functions are trivially testable and easy to reason about.
You have four options: function declaration (function foo() {}) - hoisted and callable anywhere in its scope; function expression (const foo = function() {}) - not hoisted; arrow function (const foo = () => {}) - shorter syntax and lexical this; and the Function constructor - basically never use this in real code since it evaluates a string. In modern code, declarations and arrow functions cover 95% of use cases.
A function expression is a function assigned to a variable rather than declared standalone - const double = function(x) { return x * 2; }. Because it's assigned like any other value, it's not hoisted, so you can only call it after the line it's defined on. You can give function expressions a name (useful for stack traces in debugging), but the name is only accessible inside the function itself.
An anonymous function has no name - common as inline callbacks where you don't need to reuse the function elsewhere. You see them constantly in array methods (arr.map(x => x * 2)), event listeners, and promise chains. The downside is that unnamed functions show up as 'anonymous' in stack traces, which can make debugging harder - so if a callback is complex or reused, give it a name.
The main practical difference is hoisting - declarations are fully hoisted so you can call them before they appear in the code, which can be convenient but also surprising. Expressions aren't hoisted, enforcing a clear 'define before use' order. Most style guides prefer function declarations for top-level reusable functions, and expressions (usually arrow functions) for inline or callback use.
The critical difference is this binding. Regular function expressions get their own this set by how they're called - which causes the classic 'lost context' bug in callbacks and event handlers. Arrow functions capture the this from the enclosing scope at definition time and never change it. Arrow functions also can't be used as constructors and don't have their own arguments object.
Parameters are the names in the function definition - they're placeholders. Arguments are the actual values you pass when calling the function. In function add(a, b), a and b are parameters; in add(2, 3), 2 and 3 are arguments. Easy to mix up verbally, but it matters in interviews and when reading docs about rest parameters vs rest arguments.
Callback hell is when you nest async callbacks three, four, or five levels deep because each operation depends on the previous one's result - you get a triangle of doom that's nearly impossible to read or debug. It was a real problem before Promises and async/await existed. The fix is to use async/await or chain Promises - both flatten the nesting into sequential-looking code that's much easier to follow.
setTimeout(fn, delay) schedules a function to run once after delay milliseconds, returning a timer ID. Pass that ID to clearTimeout(id) to cancel it before it fires - this is important in React components to avoid calling setState after a component has unmounted. Note that the delay is a minimum, not a guarantee - if the main thread is busy, the callback fires later.
setInterval(fn, delay) calls your function repeatedly every delay milliseconds until you stop it. Always capture the returned ID and call clearInterval(id) when you're done - forgetting to clear it is a common memory leak. One gotcha: if your callback takes longer to run than the interval delay, calls can pile up. For that pattern, chain setTimeout calls recursively instead.
Debouncing delays execution until a burst of events stops - each new event resets the timer. The classic example is a search box: you don't want an API call on every keystroke, just when the user pauses typing. Implement it by clearing and resetting a setTimeout on each event. Libraries like Lodash have a battle-tested _.debounce() utility, so use that rather than rolling your own.
Throttling limits how often a function fires regardless of how many events come in - like allowing a call at most once every 200ms. Unlike debouncing (which waits for silence), throttling guarantees regular execution during continuous events. Use it for scroll or mousemove handlers where you want smooth, regular updates without hammering the browser. Lodash's _.throttle() is the pragmatic choice for production code.
this usually depends on how a regular
function is called, not where it is defined. In an
object method call such as obj.method(), it
is obj; in a plain call it is
undefined in strict mode and may be the
global object in a non-strict script. Arrow functions
do not have their own this; they capture it
from the surrounding scope. Class methods also use the
call-site rule, so passing one as a callback can lose
its receiver unless it is bound.
JavaScript only returns one value, but that value can be an array or object carrying multiple pieces of data. Return an array when order matters (like useState does: return [value, setter]), or return an object when you want named properties for clarity. At the call site, destructure immediately: const [x, y] = getCoords() or const { width, height } = getDimensions(). Returning an object is usually clearer since callers don't need to remember the order.
this refers to the object that is currently running the code. Its value depends on how a function is called, not where the function is written. It can be the global object, an object instance, or something explicitly set using call, apply, or bind.
A regular function has its own this, which is determined by how it is called. An arrow function does not have its own this at all. It inherits this from the surrounding code where it was written. This is why arrow functions are often used for callbacks inside class methods, but an arrow function is usually the wrong choice for an object method that needs the object as this.
const obj = {
name: "Alice",
regularFn: function () {
console.log(this.name); // "Alice" - this is obj
},
arrowFn: () => {
console.log(this.name); // usually undefined - arrow captured outer this
},
};
obj.regularFn();
obj.arrowFn();
function runLater() {
this.name = "Bob";
setTimeout(() => console.log(this.name), 0); // Bob
}
runLater.call({ name: "" });
All three let you manually set what this should be inside a function. The difference is when and how they call the function.
- call() - calls the function right away, arguments passed one by one
- apply() - calls the function right away, arguments passed as an array
- bind() - does not call the function immediately, returns a new function with
thispermanently set
function greet(greeting) {
console.log(greeting + ", " + this.name);
}
const user = { name: "Alice" };
greet.call(user, "Hello"); // Hello, Alice
greet.apply(user, ["Hi"]); // Hi, Alice
const boundGreet = greet.bind(user);
boundGreet("Hey"); // Hey, Alice
Inside a class method, this refers to the instance of that class. So if you create const user = new User(), then inside any method of User, this points to user. However, if you pass a method as a callback and call it without the object context, this can get lost.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
console.log(this.count);
}
}
const c = new Counter();
c.increment(); // 1 - this is c
When you pass a method as a callback, you are passing the function itself, not the object it belongs to. So when the callback runs, it is called as a plain function, and this becomes undefined (in strict mode) or the global object. Fix this with .bind() or by using an arrow function.
class Timer {
constructor() {
this.seconds = 0;
}
start() {
// "this" is lost here because setTimeout calls the function standalone
setTimeout(function () {
this.seconds++; // TypeError: Cannot set property of undefined
}, 1000);
// Fix 1: arrow function inherits this
setTimeout(() => {
this.seconds++;
}, 1000);
// Fix 2: bind
setTimeout(function () {
this.seconds++;
}.bind(this), 1000);
}
}
If a property value is a function, undefined, or a Symbol, it is silently removed from the result. If the top-level value itself is a function or undefined, stringify returns undefined (not a string).
const obj = {
name: "Alice",
greet: function () { return "hello"; },
score: undefined,
};
console.log(JSON.stringify(obj));
// '{"name":"Alice"}' - greet and score are gone
A function retains access to bindings from its lexical scope, allowing those bindings to persist between calls. If a long-lived closure keeps references to large objects or detached DOM nodes that are no longer needed, those objects cannot be reclaimed until the references are released.
Composition combines functions so the output of one becomes the input of another. Currying transforms a function that accepts multiple arguments into a sequence of functions that each accept one argument; either technique can support reusable functional pipelines.
JavaScript Practical and Coding Interview Questions
Problem: Implement compose(...functions) so compose(f, g)(value) evaluates f(g(value)). Demonstrate it by doubling 5 and then formatting the result.
const compose = (...functions) => (value) =>
functions.reduceRight((result, fn) => fn(result), value);
const double = (value) => value * 2;
const label = (value) => 'Result: ' + value;
console.log(compose(label, double)(5));