Interview Q&A · JavaScript · 12 questions in this topic
Functions In Depth — JavaScript Interview Q&A
How functions really work — declarations, arrows, defaults, rest/spread and first-class usage. Part of Functions & Closures · 204 questions in the JavaScript bank.
What are the ways to define a function (and how do they differ)?
Answer
Declarations (function f(){}) hoist whole and name themselves. Expressions (const f = function(){}) follow variable hoisting (TDZ for const). Arrows ((x) => x) bind lexically (no own this/arguments) and suit callbacks. Methods (shorthand in objects/classes) get proper this plus super access.
Declarations for standalone APIs, arrows for callbacks, methods for objects.
Example
function add(a, b) { return a + b; } // hoisted declaration const mul = (a, b) => a * b; // lexical arrow const o = { name: 'x', hi() { return this.name; } }; // method
💡 Hoisting plus this-binding is the two-axis comparison.
How do arrow functions differ from regular functions?
Answer
Arrows capture this/arguments lexically (no own bindings), cannot be constructors (no new, no prototype), have no arguments object (use rest), and return implicitly with concise bodies. Regular functions get dynamic this, arguments, and constructability.
Arrows for callbacks/inline logic; regular functions for methods needing this and constructible types.
Key points
- 1this — lexical (arrow) vs dynamic (regular).
- 2Construct — arrows cannot (no new).
- 3arguments — arrows lack it (rest instead).
Example
const o = { v: 1, a: () => this.v, // undefined: lexical this (module/global) b() { return this.v; } // 1: dynamic this (o) };
How do default parameters, rest and spread work?
Answer
Defaults (f(a = 1)) fill undefined (not null) at call time with fresh evaluation per call (mutable defaults are call-fresh, unlike Python). Rest (...args) gathers trailing arguments into an array. Spread (...arr) expands iterables into calls/literals.
Defaults-plus-destructuring gives named-options patterns; rest/spread replaced arguments/apply.
Example
function f(a = 1, ...rest) { return [a, rest]; } f(); // [1, []] (undefined triggers default) f(null); // [null, []] (null does NOT) const m = Math.max(...[1, 9, 3]); // 9
What is the `arguments` object and why is rest better?
Answer
arguments is the array-like (indexed, .length, no map) of all passed arguments — with legacy callee/caller baggage and non-arrow-only availability. Rest (...args) is a real array with methods, works in arrows, and declares intent in the signature.
New code uses rest; arguments appears only in legacy/varargs-compat reading.
Example
function old() { return arguments.length; } // array-like, no .map const neu = (...args) => args.map((x) => x * 2); // real array
💡 Real-array plus arrow-compatible is why rest won.
What does it mean that functions are first-class?
Answer
Functions are values: assignable, passable as arguments (callbacks), returnable (factories, decorators), and storable in objects/arrays. Callbacks, promises, array methods and middleware all rest on this.
Higher-order functions (taking/returning functions) plus closures are the paradigm this enables.
Example
const run = (fn, x) => fn(x); // higher-order: takes a function const twice = (fn) => (x) => fn(fn(x)); // returns a function run((n) => n + 1, 5); // 6
What is an IIFE and what problem did it solve?
Answer
An Immediately Invoked Function Expression ((function(){...})()) runs once, scoping its internals — the pre-module privacy pattern (no global leaks before ES modules). Modern use survives for one-shot async setup (async IIFE) and isolated scopes.
Modules replaced the privacy role; async-IIFE remains the top-level-await workaround where unsupported.
Example
(function () { const secret = 1; // not global (pre-module privacy) })(); // modern: (async () => { await init(); })();
💡 Pre-module privacy is the history; async-setup is the surviving use.
What is the difference between `call`, `apply` and `bind`?
Answer
call invokes now with listed args (fn.call(ctx, a, b)). apply invokes now with array args (fn.apply(ctx, [a, b]) — the spread predecessor). bind returns a bound copy (fixed this plus partial args) for later invocation.
Borrow methods (Array.from on array-likes), fix callbacks' this, and partially apply handlers.
Example
function hi(g) { return `${g}, ${this.name}`; } hi.call({ name: 'Al' }, 'Hey'); // immediate, listed const later = hi.bind({ name: 'Bo' }); // deferred, bound later('Hi');
💡 Now-listed, now-array, later-bound is the trio summary.
What is currying / partial application?
Answer
Currying transforms f(a,b) into f(a)(b) — one argument per call, enabling staged configuration. Partial application fixes some arguments now (bind, arrow wrappers) leaving the rest. Both specialize generic functions into focused ones (event handlers, configured loggers).
Arrows make both one-liners; lodash-style curry helpers automate the rest.
Example
const add = (a) => (b) => a + b; // curried const add5 = add(5); add5(3); // 8
What are pure functions and why do they matter?
Answer
Pure functions return solely from inputs with no side effects — same args, same result, every time. They test trivially, memoize safely, parallelize freely, and reason locally. Impure necessities (I/O, randomness, DOM) get pushed to boundaries, keeping cores pure.
Purity is the testability-and-reasoning property functional code is built on.
Example
// pure: testable, cacheable const total = (items) => items.reduce((s, i) => s + i.price, 0); // impure: reads clock/DOM/network
💡 Same-in-same-out plus no-side-effects is the definition pair.
How do you memoize a function (and when does it backfire)?
Answer
Cache results keyed by serialized arguments (Map with JSON keys, or nested Maps/WeakMaps for objects) — repeated calls return cached values. Backfires on huge/unique argument streams (unbounded memory — add LRU caps), impure functions (stale lies), and object-identity keys (WeakMap for GC-friendly caching).
Pure, repeated, expensive calls memoize; everything else needs eviction policy.
Example
const memo = (fn) => { const c = new Map(); return (...a) => { const k = JSON.stringify(a); if (!c.has(k)) c.set(k, fn(...a)); return c.get(k); }; };
What is debouncing vs throttling?
Answer
Debounce waits for silence (fires after calls stop — search-as-you-type, resize-end). Throttle caps rate (fires at most every N ms during continuous calls — scroll handlers, live saves). Both wrap handlers with timers; leading/trailing options pick edge behavior.
Idle-detection wants debounce; steady-sampling wants throttle.
Key points
- 1Debounce — fire after quiet (search input).
- 2Throttle — fire at capped rate (scroll).
- 3Edges — leading/trailing options.
Example
const debounce = (fn, ms) => { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; };
How do callbacks work, and what is callback hell?
Answer
Callbacks are functions passed to run later (event handlers, async completions). Nesting them for sequential async steps creates callback hell — rightward-drifting, error-handling-scattered pyramids. Promises flatten chains; async/await makes them read synchronous.
Hell is a shape problem (nesting), fixed by returning promises instead of nesting callbacks.
Example
// pyramid (hell): // getUser(id, (u) => getOrders(u, (o) => render(o))); // flat (promise chain): // getUser(id).then(getOrders).then(render).catch(show);
💡 Return-don't-nest is the escape rule.
Recommended resourcesAffiliate links · may earn us a commission