Javascript
161 bites tagged Javascript — interview questions with model answers, and 60-second explainers.
Write a fetch call and log JSON from the Response
This tests async HTTP literacy and fetch's two-stage promise resolution. A strong answer awaits fetch, then awaits response.json(), logs result, and notes fetch does not throw on 4xx/5xx.
How do you fetch from three APIs using Promise.all versus allSettled?
Promise.all parallelizes but rejects on first failure. allSettled returns every outcome with status, value, and reason. Promise concurrency and failure isolation. Wrapping each call in try-catch to imitate allSettled.
How do you wrap a callback-based API into a Promise?
This tests Promise constructor mechanics and callback migration. A strong answer returns a new Promise, calls the legacy function, maps success to resolve and errors to reject.
Why does this lose context in class callbacks and two TypeScript fixes?
This tests runtime this binding. Explain that regular functions get this from the call site, so passing a method strips its object context. Fix with an arrow property or constructor bind. Red flag: var self = this or claiming TypeScript changes binding.
Offload CPU-intensive work to a Web Worker and explain communication.
This tests main-thread blocking and worker messaging. A strong answer covers: new Worker(url), moving logic to a worker file, sending data via postMessage(), and receiving results via onmessage. A red flag is suggesting DOM use or shared memory from workers.
What are the key differences between NodeList and HTMLCollection?
Tests DOM snapshot vs live binding: querySelectorAll returns a static NodeList, getElementsByTagName returns a live HTMLCollection. Strong answers note childNodes is a live NodeList and warn against caching length during DOM mutation.
Explain DOM event capturing and bubbling with addEventListener
Tests DOM event propagation and addEventListener phase selection. Core: capture moves root-to-target, bubble moves target-to-root, useCapture or options.capture sets it. Red flag: saying events only bubble or confusing stopPropagation with preventDefault.
What happens when you declare var globally versus let or const?
Knowledge that var creates a Window property while let and const do not. A good answer notes var adds window.x, let/const do not pollute the global object, yet both are globally scoped. claiming let/const lack global scope.
What is the fundamental difference between window and document?
Window is the browser tab and global scope; document is the object-oriented DOM representation of the loaded page. Your mental model of the browser runtime layers.
ES Modules in TypeScript: The Compile-Time Contract
TypeScript ES modules are a compile-time target, not a runtime guarantee. Configure this when targeting modern browsers or Node with native ESM. The footgun is omitting .js extensions in imports, which it requires in ESM output even for .ts source files.
Worker postMessage: The Structured Clone Pipe
Worker postMessage moves data between threads via structured cloning. Use it to offload heavy work without blocking the UI. The message argument is mandatory, so omitting it is an error and you must pass null when there is no data.
Next.js 16.2 brings 67-100% faster server Fast Refresh
Next.js 16.2 Turbopack brings Server Fast Refresh to Node.js, cutting reload times 67-100% and compile times 400-900%. Only changed modules reload, not whole chains. WASM Workers, SRI, and dynamic import tree shaking land; upgrade to cut dev latency.
Difference between jest.fn, jest.spyOn, and jest.mock in React
Tests whether you distinguish Jest's three mocking scopes. Good answers: jest.fn for standalone callbacks; jest.spyOn to observe existing methods; jest.mock to swap entire modules. Red flag: using them interchangeably or saying spyOn replaces modules.
Rules of Hooks: Call Order Is Sacred
Hook calls must keep the same order every render because React maps them to state by array index. Only call hooks at the top level of React functions. Break the order and React desyncs, producing stale state or crashes.
Callback Hell: The Pyramid of Doom
Callback hell is what happens when nested async callbacks indent so deeply the code forms an unreadable pyramid. You see it in legacy Node.js when chaining database queries or file reads.
How do you trigger a CSS transition? Provide two methods.
Set transition on the element, then change a property via :hover or by toggling a class with JavaScript. That you know a transition needs a property change to fire, not just a declaration.
CSS-in-JS: Scoped Styles via JavaScript
CSS-in-JS lets components own their styles in JavaScript, generating CSS and injecting it into the DOM at runtime. It prevents global namespace collisions in component frameworks. The footgun is runtime overhead and bigger bundles.
Build a dynamic table of contents from article h2 tags
Query h2s with querySelectorAll, assign ids, map to anchor links, append a nav list. Basic DOM querying and dynamic element creation in vanilla JS. Importing jQuery or a framework for a six-line native task.
How would you track clicks on headlines and calls-to-action?
This tests DOM event handling and basic telemetry design. A strong answer covers event delegation with addEventListener, data attributes for element IDs, and a payload with timestamp and page context.
Vitest Mocking: Isolating Code with `vi.mock`
Vitest's `vi.mock` replaces a module with a fake version, isolating your code for tests. This is key for preventing real network or database calls. The footgun: calls are "hoisted" to the top of the file, running before other code and breaking variable access.
The Testing Trophy: Prioritize Integration Tests
The Testing Trophy flips the classic pyramid, arguing for "mostly integration tests" to maximize your return on investment. It's for UI apps where testing component interactions gives more confidence than isolated unit tests.
JavaScript Bundle Analysis: Seeing Your App's Weight
Think of it as an X-ray for your compiled JavaScript, showing which libraries take up the most space. Use it to diagnose slow load times by finding large or duplicated dependencies.
Vue Render Functions: Trading Templates for JS Power
Render functions trade Vue's declarative templates for the full programmatic power of JavaScript. Use them for highly dynamic components where logic is too complex for templates. The footgun is losing template optimizations and readability for imperative code.
Vue Composables: Reusable Stateful Logic
A Vue composable is a function for bundling reusable stateful logic, like tracking mouse position. Use it to share complex logic like API fetches across components. The footgun: each component gets a fresh, independent state, not a shared one.
Get Javascript bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.