Interview Q&A · JavaScript · 12 questions in this topic

Functions In Depth — JavaScript Interview Q&A

All JavaScript topics

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

Example.jsjs
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

  1. 1this — lexical (arrow) vs dynamic (regular).
  2. 2Construct — arrows cannot (no new).
  3. 3arguments — arrows lack it (rest instead).

Example

Example.jsjs
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

Example.jsjs
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

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits