JavaScript interview questions
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
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.