Lesson 15 of 32Question banks
JavaScript and TypeScript Questions
Answer the classic JS and TS interview questions on closures, this, the event loop, and the type system.
Frontend and full-stack interviews love short JavaScript puzzles: "what does this print?", "why is this undefined here?", "what is the difference between unknown and any?". They take two minutes to ask and they separate people who have memorised syntax from people who understand the runtime. Here are the ones that come up most, with answers you can say out loud.
Scope: var, let, const, and hoisting
"What is the difference between var, let, and const?" var is function-scoped and can be redeclared. let and const are block-scoped (they live inside the nearest { }). const cannot be reassigned, though the object it points to can still be mutated. In modern code, use const by default and let when you must reassign; avoid var.
"What is hoisting?" Before code runs, JavaScript sets up every declaration in a scope. function declarations are hoisted with their body, so you can call them before the line they are written on. var is hoisted and initialised to undefined. let and const are hoisted but not initialised: touching them before their line throws a ReferenceError. The gap between the start of the scope and the declaration is the temporal dead zone.
What does this print?
console.log(typeof greet);
console.log(count);
var count = 5;
function greet() { return "hi"; }for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}Closures and this
"What is a closure?" A function bundled with the variables from the scope where it was created. The inner function keeps access to those variables even after the outer function has returned. Closures power private state, factories, memoisation, and every React hook.
Press Run (⌘ Enter) to see what happens."How is this determined?" By how a function is called, not where it is written (except arrow functions):
| Call | this is |
|---|---|
obj.method() | obj |
fn() plain call | undefined in strict mode and modules (the global object in sloppy scripts) |
new Fn() | the new object |
fn.call(x), fn.apply(x), fn.bind(x) | x |
| Arrow function | whatever this was in the enclosing scope (arrows have no own this) |
Model answer: == vs ===
=== is strict equality: same type and same value, no conversion. == is loose equality: if the types differ, it converts them first, which gives surprises like 0 == "" (true) and "1" == 1 (true). Always use ===; the one common exception is x == null, which is true for both null and undefined. Also know that NaN === NaN is false (use Number.isNaN), and objects are compared by reference, so {} === {} is false.
Model answer: prototypes
Every object has a hidden link to another object, its prototype (Object.getPrototypeOf(obj)). When you read a property that is not on the object, JavaScript walks up this prototype chain until it finds it or reaches null. Methods defined in a class live on ClassName.prototype and are shared by all instances. class syntax is a cleaner way to write this same prototype-based inheritance; it is not a different model like Java classes.
Prototypes and classes, in code
The prototypes model answer above gives the idea. The follow-up is usually "so what is actually different about class?" Four things are worth saying:
- It is still a function (
typeof Dogis"function"), and its methods still live onDog.prototype, shared by every instance. - It must be called with
new. Calling an old constructor function withoutnewsilently sets properties on the wrongthis. Calling a class withoutnewthrows aTypeError. - Class bodies run in strict mode, and class methods are non-enumerable, so they do not show up in a
for...inloop. extendsandsuperset up the prototype link and the parent constructor call for you, including extending built-ins likeErrorandArraycorrectly, which was awkward with constructor functions.
Press Run (⌘ Enter) to see what happens.The last line shows the key fact: speak is not an own property of d. It is found on the prototype. That is why adding a method to Animal.prototype later makes it appear on every existing instance, and why arrow functions as class fields (speak = () => {...}) are different: they are created per instance, which costs memory but keeps this bound.
The coercion rules behind ==
The == model answer above is what you say first. Interviewers then sometimes put up a table of comparisons and ask you to fill it in. You do not need the whole spec, just the order of the rules == applies when the types differ:
nullandundefinedequal each other and nothing else.- A boolean is converted to a number first (
trueis 1,falseis 0). - If one side is a number and the other a string, the string becomes a number (the empty string becomes 0).
- An object or array is converted to a primitive, which for arrays means a string like
"1,2", and then the rules repeat. NaNequals nothing, including itself.
Match each comparison to its result.
The event loop
"Explain the event loop." JavaScript runs on one thread with a call stack. Slow work (timers, network, file I/O) is handed to the host (the browser or Node). When it finishes, its callback is queued. The event loop's rule: when the stack is empty, first run every microtask (promise callbacks, queueMicrotask, await continuations), then take one macrotask (a setTimeout callback, an I/O event), and repeat.
Synchronous code runs first. A is logged immediately.
What is the output, one item per line?
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
(async () => {
console.log("4");
await null;
console.log("5");
})();
console.log("6");Model answer: promises vs async/await
A promise is an object for a value that will exist later: pending, then fulfilled or rejected. You chain with .then() and .catch(). async/await is syntax over promises: an async function always returns a promise, and await pauses that function (not the thread) until the promise settles, letting you use normal try/catch. Use Promise.all to run independent awaits in parallel instead of awaiting them one by one, Promise.allSettled when you want every result even if some fail, and Promise.race/Promise.any for the first to finish.
Practical utilities: debounce, throttle, deep copy
Debounce waits until calls stop for N ms, then runs once (search-as-you-type, resize end). Throttle runs at most once every N ms while calls keep coming (scroll position, mouse move). Interviewers often ask you to write debounce:
Press Run (⌘ Enter) to see what happens.Model answer: deep copy
structuredClone(value) is the built-in deep copy in browsers and Node 17+. It handles nested objects, arrays, Date, Map, Set, and circular references, but not functions, DOM nodes, or class prototypes. JSON.parse(JSON.stringify(x)) is the old trick; it loses undefined, functions, Date (turns into strings), Map/Set, and fails on cycles. Spread ({ ...obj }) and Object.assign are shallow.
Implement-it questions
Frontend and full-stack screens often say "implement X from scratch". Promise.all and an EventEmitter with once are covered with model answers in Frontend Interview Rounds. Two more come up constantly.
Debounce with leading and trailing options. The basic version above only fires at the end of a burst (trailing). A common follow-up asks for leading: true, which fires on the first call so the user gets instant feedback. The trap: with both options on, a single call must fire once, not twice.
Press Run (⌘ Enter) to see what happens.Talk through the state: timer tells you whether you are inside a burst, and lastArgs remembers whether any call arrived after the leading one. Clearing lastArgs after the leading call is what stops the double fire. Lodash's debounce also has a maxWait option, which turns it into something close to throttle; mention it if you know it.
Flatten an array, with an optional depth. This tests recursion and edge cases: empty arrays inside, and stopping at a given depth.
Press Run (⌘ Enter) to see what happens.Follow-ups: "Do it without recursion" (use an explicit stack of items, and reverse at the end or push in reverse to keep order), "what about very deep nesting?" (recursion can overflow the stack, so the iterative version is safer), and "what about holes in sparse arrays?" (the built-in flat skips them).
What does flatten([1, [2, [3]]], 1) return, printed with JSON.stringify?
console.log(JSON.stringify(flatten([1, [2, [3]]], 1)));
TypeScript
Model answer: interface vs type
Both describe object shapes and are mostly interchangeable. interface can be extended with extends and merged (declaring the same interface twice combines them, useful for augmenting library types). type aliases can express things interfaces cannot: unions ("a" | "b"), tuples, mapped and conditional types. A common team rule: interface for public object shapes, type for everything else. Consistency matters more than the choice.
"any vs unknown?" Both accept any value. any turns type checking off: you can call anything on it and errors leak everywhere. unknown is the safe version: you cannot use it until you narrow it with a check like typeof x === "string". Use unknown for data from outside (JSON, user input, catch errors).
function handle(data: unknown) {
if (typeof data === "string") {
console.log(data.toUpperCase()); // line A
}
console.log(data.length); // line B
}Generics let a function or type work over many types while keeping them linked: function first<T>(xs: T[]): T | undefined returns the same type it receives. Narrowing is how TS refines a union inside a branch: typeof, instanceof, in, equality checks, and discriminated unions (a shared literal field like kind: "circle" | "square" you switch on).
Match the utility type to what it produces from type User = { id: number; name: string; email?: string }.
satisfies, conditional and mapped types
"What does satisfies do?" It checks that a value matches a type without changing the value's inferred type. A type annotation widens: const routes: Record<string, string> = {...} forgets which keys exist. satisfies keeps the narrow type and still catches mistakes.
type Theme = Record<string, `#${string}`>;
const annotated: Theme = { primary: "#000", accent: "#fff" };
annotated.primry; // no error: any string key is allowed
const checked = { primary: "#000", accent: "#fff" } satisfies Theme;
checked.primry; // error: property 'primry' does not exist
checked.primary; // type is "#000" kept narrowConditional types choose a type based on another: T extends string ? "text" : "other". With infer they extract parts of a type, which is how built-ins like ReturnType<F> and Awaited<P> are written. When T is a union, a conditional type is applied to each member separately (it distributes), so NonNullable<string | null> gives string.
Mapped types build a new object type by looping over keys: { [K in keyof T]?: T[K] } is how Partial<T> works. Add readonly, remove optionality with -?, or rename keys with an as clause and a template literal type, which is how you would turn a name field into a getName method type.
A good interview answer names a real use: "I used a mapped type to derive form-error types from the form values type, so adding a field updated both."
const config = {...} satisfies Config instead of const config: Config = {...}?Model answer: enums
A TypeScript enum creates a real JavaScript object at runtime (numeric enums even create a reverse mapping), which is one of the few TS features that is not just erased types. Many teams prefer a union of string literals (type Status = "idle" | "loading" | "done") or an as const object instead: zero runtime cost, simpler output, and it works with tools that strip types without compiling, such as Node's built-in type stripping. If you use enums, prefer string enums so values are readable in logs.
Module systems: ESM and CommonJS
"What is the difference between import and require?" They are two module systems. CommonJS (require, module.exports) was Node's original system: loading is synchronous, happens when the line runs, and require can be called anywhere, even conditionally. ES modules (import, export) are the language standard, used by browsers and by modern Node. Imports are static, so tools can analyse them before running (which enables tree shaking), they are loaded asynchronously, top-level await is allowed, and exported bindings are live: if the exporting module changes a let, importers see the new value.
In Node, a file is treated as ESM if it ends in .mjs, or ends in .js with "type": "module" in the nearest package.json. Otherwise .js is CommonJS. ESM can import CommonJS. Recent Node versions can also require() an ES module that has no top-level await, which removed much of the old pain, but check the docs for your Node version before relying on it. In ESM there is no __dirname; use import.meta.dirname in current Node, or derive it from import.meta.url.
The senior-sounding part: "New code should be ESM. The friction is mostly in libraries that must support both, which is why some packages publish dual builds with an exports map in package.json."
- prototype chain
- The linked objects JavaScript searches when a property is missing on the object itself.
classandextendsbuild on it. - satisfies
- A TypeScript operator that checks a value against a type while keeping the value's narrower inferred type.
- ES module
- The standard
import/exportmodule system: static, async-loaded, tree-shakeable, with live bindings. - hoisting
- Declarations are set up before code runs: functions with their body,
varas undefined,let/constuninitialised (temporal dead zone). - closure
- A function plus the variables from the scope where it was created, kept alive after that scope returns.
- microtask
- A high-priority callback (promise
.then, code afterawait). All run before the next macrotask. - debounce
- Run a function only after calls have stopped for N ms.
- unknown
- TypeScript's safe top type: accepts anything, but must be narrowed before use.
- discriminated union
- A union of object types sharing a literal field (like
kind) that TS uses to narrow.