JavaScript interview questions
Show answer
varis function-scoped and hoisted with the valueundefined, so it can be used before its line runs.letandconstare block-scoped and sit in the temporal dead zone until declared, so early access throws.constprevents re-assigning the variable, but an object it points to can still be mutated. Preferconst, useletwhen you must re-assign, and avoidvar.Show answer
A closure is a function that keeps access to variables from the scope where it was created, even after that scope has returned. Uses: private state (a counter factory that returns
increment), memoisation caches, and event handlers that remember a value. A classic bug is creating closures in a loop withvar— every callback sees the final value;letcreates a fresh binding per iteration.Show answer
JavaScript runs one call stack. When it is empty, the event loop first drains the microtask queue (promise callbacks,
queueMicrotask), then takes one macrotask (timers, I/O, UI events), runs it, and repeats; browsers may render between macrotasks. SoPromise.resolve().then(a); setTimeout(b)runsabeforeb. Long synchronous work blocks everything, including rendering.Show answer
==converts both sides to a common type before comparing; an empty string converts to the number 0. These coercion rules are hard to remember, so use===, which compares type and value without conversion.Object.isadditionally treatsNaNas equal to itself and distinguishes+0from-0.Show answer
It depends on how a function is called: as a method (
obj.fn())thisisobj; called plainly it isundefinedin strict mode; withnewit is the new object;call/apply/bindset it explicitly. Arrow functions do not have their ownthis— they use the surrounding one, which is why they are handy for callbacks inside classes.Show answer
function debounce(fn, ms) { let t; return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); }; }Debounce runs the function once activity stops for
ms(search-as-you-type). Throttle runs it at most once everymswhile activity continues (scroll position tracking). Mention cancelling on unmount and preservingthisif needed.