Skip to main content

Frontend engineer technical fundamentals interview questions

25 questions on technical fundamentals for frontend engineer candidates. Expect prompts such as “Explain how CORS and preflight requests work” and “How does CSS specificity work and what is the cascade?”, each with a worked answer outline and the follow-ups interviewers push on.

Questions

Showing 1 to 25 of 25 technical fundamentals questions.

As asked

Your React app on app.example.com fetches from api.example.com. Explain what CORS is, when a preflight OPTIONS request is triggered versus not triggered, and what the server must include in its response headers to allow the request.

Sample answer outline

CORS is the browser policy restricting cross-origin requests. Simple requests (GET/POST with basic content types) are sent directly; the browser checks the response Access-Control-Allow-Origin. Preflighted requests occur for methods like PUT/DELETE or custom headers; the browser sends OPTIONS first. Server must respond with ACAO, ACAM, and ACAH headers. Should mention that CORS is enforced by the browser, not the server.

Expect these follow-ups

  • What is the wildcard in Access-Control-Allow-Origin and when can you not use it?
  • How would you configure CORS in a Next.js API route or middleware?
httpcorssecuritybrowserfundamentals

As asked

Explain the specificity hierarchy in CSS from least to most specific. Given a selector conflict, how does the browser resolve which rule wins? What is the cascade and what factors does it consider besides specificity?

Sample answer outline

Specificity is calculated as (inline styles, ID selectors, class/attribute/pseudo-class, element/pseudo-element). Cascade order: origin (user agent, user, author), importance, specificity, source order. Layers added in CSS @layer change the cascade without affecting specificity. Should know that :not() and :is() take the specificity of their most specific argument.

Expect these follow-ups

  • What is the :is() pseudo-class and how does it affect specificity compared to a comma-separated selector list?
  • How does @layer change the cascade and why was it introduced?
cssspecificitycascadefundamentals

As asked

Define what a closure is in JavaScript, explain when one is created, and give me a concrete example from frontend code where understanding closures is necessary to write correct code.

Sample answer outline

A closure is created when a function is defined inside another scope and retains a reference to that scope's variables even after the outer function has returned. Practical example: a React useEffect that captures state variables at creation time, or a for-loop with var that causes all event listeners to share the same loop variable.

Expect these follow-ups

  • How does the garbage collector decide when a closure's captured variables can be freed?
  • Explain the classic var-in-a-loop bug and two ways to fix it.
javascriptclosuresfundamentalsscope

As asked

Without running it, tell me the output order of this code and explain why: console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');

Sample answer outline

Output: A, D, C, B. A and D are synchronous and run first. Promise.then goes to the microtask queue and runs after the current synchronous script but before any new tasks. setTimeout callback is a task and runs in a later event loop turn.

Expect these follow-ups

  • What if the Promise.resolve was replaced with a native async function that awaits another promise? Would C still come before B?
  • What would happen if you nested two Promise.then callbacks before the setTimeout fires?
javascriptevent-looppromisesfundamentalsasync

As asked

Explain how Swift's value types and reference types interact with ARC. In a closure that captures self in a view controller, how does a retain cycle form and how do you break it?

Sample answer outline

A strong answer distinguishes structs and enums as value types copied on assignment from classes as reference types tracked by ARC. It explains that a retain cycle forms when a closure captures a strong reference to self and self holds a strong reference to the closure. The fix is a capture list with weak or unowned: weak when self may become nil before the closure runs, unowned when you can guarantee it will not. The candidate should mention that structs never participate in retain cycles because they have no reference count.

Reference implementation (swift)

Swift
class ViewModel {
    var onUpdate: (() -> Void)?
}

class ViewController: UIViewController {
    var viewModel = ViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Retain cycle: closure captures self strongly,
        // self holds viewModel, viewModel holds the closure.
        viewModel.onUpdate = { [weak self] in
            guard let self = self else { return }
            self.updateUI()
        }
    }

    func updateUI() {}
}

Expect these follow-ups

  • When would you choose unowned over weak?
  • How do you detect retain cycles in Instruments?
company:appleswiftarcmemory-managementios

As asked

In SwiftUI, what is the difference between @State, @StateObject, and @ObservedObject? What goes wrong if you use @ObservedObject to own the model instead of @StateObject?

Sample answer outline

@State is for primitive value types owned and managed by the view itself. @StateObject creates and owns an ObservableObject for the lifetime of the view; the view is the source of truth. @ObservedObject subscribes to an ObservableObject owned elsewhere. The bug when using @ObservedObject to own is that SwiftUI may re-create the view struct on each re-render, which destroys and recreates the object, resetting all state. The candidate should be able to say this is one of the most common bugs beginners hit in production SwiftUI apps.

Expect these follow-ups

  • How does the @Observable macro in iOS 17 change this picture?
  • When would you lift state to @EnvironmentObject?
company:appleswiftuistate-managementiosswift

As asked

A Coinbase transaction fee is 1.49% of the trade amount. A user buys 0.00312 BTC at $42,385.50 per BTC. Your backend calculates the fee in JavaScript using floating-point arithmetic. What can go wrong and how do you fix it?

Sample answer outline

The candidate should explain that IEEE 754 floating-point representation cannot exactly represent many decimals (0.1 + 0.2 !== 0.3 in JS), which means fee calculations can be off by fractional cents at scale. The fix is to use integer arithmetic in the smallest unit (satoshis for BTC, cents for USD) or a big-decimal library like Decimal.js or bignumber.js. They should also mention how the fee should be rounded (floor, ceil, or banker's rounding) and that the rounding rule should be consistent with regulatory requirements.

Expect these follow-ups

  • If a user makes 10,000 trades per day, what is the worst-case cumulative error from naive float arithmetic?
  • How do you test your fee calculation code to catch rounding bugs before production?
company:coinbasetechnical-fundamentalsprecisionfintechjavascriptarithmetic

As asked

Figma's engineering team receives reports that about 100 users are experiencing a crash when opening a specific file type, but your local reproduction attempts have all failed. The crash shows up only in production. How do you investigate, and what instrumentation or tools do you use?

Sample answer outline

A strong answer covers structured investigation: gather signal from error reporting (Sentry or Datadog) to find the common stack trace, correlate with attributes like browser version, OS, file size, and network conditions to find what the 100 affected users have in common. If a specific file is implicated, request a copy (with user consent) and test with that. Add targeted logging around the suspected code path and deploy behind a feature flag to the affected cohort. A great answer discusses how to safely add canary instrumentation to production without adding latency to the hot path, and how to communicate status to affected users during the investigation.

Expect these follow-ups

  • What if the crash is non-deterministic and only occurs 1 in 1000 times, making even targeted reproduction difficult?
  • How do you decide when to declare the issue resolved and remove the extra instrumentation?
company:figmadebuggingproduction-incidentsobservabilitybehavioralengineering-process

As asked

Explain CSRF, CORS, and CSP. What does each one protect against, and where do they overlap?

Sample answer outline

CSRF: attacker tricks a logged-in user's browser into sending an authenticated request to your site. Mitigation: SameSite cookies (Lax by default in modern browsers makes most CSRF dead), CSRF tokens for state-changing requests, or rely on the fetch+JSON path which requires CORS. CORS: governs whether a script on origin A can read responses from origin B. CORS does NOT prevent the request being sent, only restricts the response from being read. CSP: declares which sources of content are allowed; mitigates XSS by blocking inline scripts and unknown script sources. Overlap: SameSite + CSRF tokens overlap on CSRF; CORS and CSP overlap on resource loading.

Reference implementation (http)

http
// Session cookie defaults
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/

// CSP for a typical React SPA (no inline scripts, hashed styles)
Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'sha256-...';
  style-src 'self' 'sha256-...';
  img-src 'self' data: https://cdn.example.com;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  base-uri 'self';
  form-action 'self';
  report-uri /csp-report

// CORS for a same-account API (only the SPA origin is allowed)
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PATCH, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization

Expect these follow-ups

  • Why does SameSite=Lax not fully kill CSRF?
  • How would you write a CSP for a React SPA that uses inline styles?
  • When does CORS preflight not happen?
csrfcorscspweb-security

As asked

Explain the difference between Cache-Control max-age and ETag/If-None-Match as HTTP caching mechanisms. When does max-age prevent a request from being made at all, and when does ETag save bandwidth but still require a round trip?

Sample answer outline

max-age means the browser will not make a network request until the age expires. ETag is a conditional request: the browser always makes a network request but sends the ETag value; if the resource has not changed the server returns 304 Not Modified with no body. For static assets, use max-age with content-hashing; ETag is better for dynamic resources.

Expect these follow-ups

  • What is the purpose of Cache-Control: no-cache versus no-store?
  • How do you cache an HTML document differently from a JavaScript chunk in a deployment pipeline?
httpcachingbrowserperformancefundamentals

As asked

Compare localStorage, sessionStorage, cookies, IndexedDB, and Cache API. For each one, describe its storage limit, persistence, accessibility (main thread vs. service worker), and a concrete use case where it is the right choice.

Sample answer outline

localStorage: 5 to 10 MB, persists across sessions, synchronous (blocks main thread), not accessible in service workers. sessionStorage: same but per tab. Cookies: 4KB, sent with every HTTP request, accessible in SW via fetch headers, best for auth tokens (HttpOnly). IndexedDB: large structured data, async, accessible in SW, best for offline data. Cache API: response objects, SW-native, best for service worker caching.

Expect these follow-ups

  • What are the privacy implications of each storage mechanism in relation to third-party contexts and Safari's ITP?
  • Why is synchronous localStorage a performance concern and how do you work around it?
browser-apisstoragefundamentalspwa

As asked

Explain how prototypal inheritance works in JavaScript. When you access a property on an object, what is the lookup order? How does the class keyword relate to the underlying prototype chain?

Sample answer outline

Property lookup traverses the prototype chain: own properties first, then object proto (its prototype), continuing up to Object.prototype, then null. class is syntactic sugar over function constructors and Object.create; methods defined in a class body go on the prototype, not on each instance. Should cover that instanceof checks the prototype chain.

Expect these follow-ups

  • What is the difference between Object.create(proto) and new Constructor()?
  • How do you safely add a method to all arrays in a codebase without modifying Array.prototype?
javascriptprototypefundamentalsoop

As asked

From a frontend engineer's perspective, what are the concrete advantages of GraphQL over REST, and when would you actively prefer REST? Give me examples of frontend problems GraphQL solves well and problems it introduces.

Sample answer outline

GraphQL advantages: no over-fetching (request exactly the fields needed), no under-fetching (join data in one request instead of waterfall REST calls), strongly typed schema enables code generation. Problems: caching is harder (single POST endpoint bypasses HTTP caching), N+1 query risk on the server, steep learning curve. REST is better when the API is simple, caching is critical, or the backend team is small.

Expect these follow-ups

  • How does HTTP caching work differently for GraphQL queries that go over POST versus GET?
  • What is the N+1 problem in GraphQL and how does DataLoader on the server fix it?
graphqlrestapifundamentalsfrontend

As asked

Explain the key difference between CSS custom properties (variables) and Sass variables. What runtime capabilities does a CSS custom property have that a Sass variable does not, and how does this enable theming and dynamic styling?

Sample answer outline

Sass variables are resolved at compile time and produce static CSS output. CSS custom properties are resolved at runtime by the browser and can be updated via JavaScript (element.style.setProperty) or by changing a class that redefines the variable. They also cascade and inherit, so a --color-primary defined on :root can be overridden at any ancestor element for component-level theming.

Expect these follow-ups

  • What is the @property rule in CSS and what additional capability does it give to custom properties?
  • How do CSS custom properties participate in CSS animations and what limitation does this expose?
csscustom-propertiesthemingfundamentals

As asked

Design the classes and interfaces for a font management library similar to Adobe Fonts. It should support browsing fonts by family and weight, activating a font for use in an application, and tracking which fonts a user has recently used. Walk me through your class hierarchy and the responsibilities of each class.

Sample answer outline

A strong answer separates Font (a specific weight/style), FontFamily (groups fonts), FontLibrary (the collection and search interface), FontActivation (the act of making a font available), and RecentFontsTracker (a bounded history with LRU semantics). The candidate should discuss the open/closed principle when adding new activation sources (local vs cloud), and how to make FontLibrary searchable by multiple criteria without a combinatorial explosion of subclasses. They should mention the observer pattern to notify applications when fonts activate.

Expect these follow-ups

  • How do you handle a font that exists both locally and in the cloud and they are different versions?
  • How would you serialize a user's font activation state so it persists across restarts?
company:adobeoopdesign-patternsadobe-fontsobject-oriented

As asked

What problem do Swift actors solve compared to using a serial DispatchQueue with a private backing store? Walk me through what the compiler enforces and where you can still get data races.

Sample answer outline

Actors provide reference types with an implicit serial executor and compile-time enforcement: the compiler rejects synchronous access to actor-isolated state from outside the actor without await. A serial DispatchQueue achieves the same serial execution but requires manual discipline: nothing stops you from capturing the backing store directly. The candidate should know that actors can still produce races through Sendable violations, for example passing a non-Sendable class across actor boundaries, and that MainActor is a global actor backed by the main thread.

Expect these follow-ups

  • What does the Sendable protocol enforce and how does the compiler check it?
  • When would you use a nonisolated function inside an actor?
company:appleswiftconcurrencyactorsdata-racesios

As asked

The Figma Plugin API exposes complex node types with dozens of optional and required properties. Write a TypeScript generic utility type DeepPartial<T> that makes every property at every level of nesting optional. Then write a function that deep-merges two partial nodes, with the second argument taking priority on conflicts.

Sample answer outline

A strong answer correctly defines DeepPartial<T> using a mapped type that conditionally recurses into object types while leaving primitives, arrays, and function types alone. The deep merge function should use recursion, handle null vs undefined correctly, and not mutate either input. A great candidate discusses edge cases: merging arrays (overwrite vs concatenate), merging class instances (prototype chain), and the behavior when one side has a key with value undefined vs the key being absent.

Reference implementation (typescript)

TypeScript
type DeepPartial<T> = {
  // your implementation
};

function deepMerge<T extends object>(
  base: DeepPartial<T>,
  override: DeepPartial<T>
): DeepPartial<T> {
  // your implementation
}

Expect these follow-ups

  • How does your DeepPartial handle an array property like children?: FigmaNode[], should it become (Partial<FigmaNode>)[] or just FigmaNode[]?
  • What happens if you pass a deeply nested class instance instead of a plain object to your merge function?
company:figmatypescriptgenericsutility-typescodingfigma-plugin-api

As asked

Your team's CI pipeline has a 25 percent flaky-test rate, meaning 1 in 4 builds fails due to test non-determinism rather than real bugs. Engineers are re-running builds as a habit and starting to ignore red builds. How do you diagnose and fix this?

Sample answer outline

Strong answers start with classification (identify which tests are flaky, categorize causes: timing dependencies, shared state, external service calls, random data), apply targeted fixes (deterministic seeding, mocking external calls, test isolation, retry-with-detection rather than blind retry), and track flakiness rate as a metric on a dashboard. They also describe the cultural fix: quarantine chronically flaky tests rather than let them erode trust in the suite.

Expect these follow-ups

  • How do you get engineers to actually fix flaky tests rather than just quarantine them forever?
  • What would you instrument to catch a new flaky test within 24 hours of it being introduced?
company:lyfttestingci-cdreliabilityengineering-culture

As asked

You are reviewing a TypeScript codebase and see generics used without constraints, causing type errors that only appear at runtime. Explain what generic constraints are, give a concrete example of a bug they prevent, and show how you would fix the offending code.

Sample answer outline

A strong answer explains that constraints with 'extends' restrict the type parameter to a subset of types, letting the compiler verify property accesses at compile time rather than at runtime. A concrete bug: a generic function accessing .length on T without constraining T to { length: number } compiles but throws at runtime for number inputs. The fix adds the constraint. The candidate should also contrast constraints with conditional types and mapped types for bonus depth.

Expect these follow-ups

  • What is the difference between T extends object and T extends Record<string, unknown>?
  • When would you use a conditional type instead of a constraint?
company:microsofttypescriptgenericstype-safetyfrontend

As asked

You are reviewing a new service that uses OAuth 2.0 Authorization Code flow integrated with Azure Active Directory. The developer stores the access token in localStorage, does not validate the state parameter, and forwards the token to a third-party analytics service. Identify every security issue you see and explain how to fix each one.

Sample answer outline

Three issues: localStorage is vulnerable to XSS attacks because any injected script can read it, the fix is to use httpOnly cookies or in-memory storage. Not validating the state parameter opens the app to CSRF attacks on the authorization endpoint, the fix is to generate a cryptographically random state, store it in session, and verify it on redirect. Forwarding the access token to a third-party service exposes it to a potentially untrusted party that could impersonate the user, the fix is to never share access tokens and to use scoped tokens with minimum permissions.

Expect these follow-ups

  • How do you securely handle token refresh in a single-page application?
  • What is PKCE and when is it required vs. recommended in the auth code flow?
company:microsoftsecurityoauthazure-adauthentication

As asked

Netflix's Android app uses Kotlin coroutines extensively. Explain what structured concurrency means in the coroutines model, how it differs from unstructured concurrency with raw threads, and describe a bug you have seen or could imagine where improper coroutine scope usage causes a resource or memory leak.

Sample answer outline

Structured concurrency means that coroutines are always scoped to a parent and the parent cannot complete until all its children complete or are cancelled. The bug the interviewer is probing for is the classic GlobalScope.launch pattern: a coroutine launched in GlobalScope outlives its parent Activity or ViewModel, holds a reference to a destroyed View, and causes a memory leak or a crash when it tries to update UI that no longer exists. The fix is to use viewModelScope or lifecycleScope so the coroutine is automatically cancelled when the owner is destroyed.

Expect these follow-ups

  • How does coroutine cancellation propagate, and what do you need to do in a coroutine that does CPU-bound work to make it cancellation-cooperative?
  • What is the difference between coroutineScope and supervisorScope, and when would you choose one over the other?
company:netflixkotlincoroutinesandroidconcurrencymemory-leaks

As asked

A merchant asks why they need to use Stripe.js and Stripe Elements instead of building their own card input form and sending raw card numbers to Stripe's API. Explain technically how Stripe.js works under the hood and what security properties it provides.

Sample answer outline

A strong answer explains that Stripe.js renders the card fields inside a cross-origin iframe hosted on stripe.com, so the merchant's JavaScript context never has access to the raw PAN. Stripe.js tokenizes the card number client-side and returns only a token to the merchant's origin. This removes the merchant from PCI DSS scope for card data storage and transmission. The candidate should mention the Content Security Policy considerations and how Stripe.js signals readiness and errors back to the parent page without exposing card data.

Expect these follow-ups

  • How does Stripe.js pass the card token back to the parent page from inside its iframe securely?
  • What is the difference between a card token, a PaymentMethod, and a PaymentIntent?
company:stripestripe-jssecuritypci-dssfrontendpayments

As asked

Explain what TLS does for a browser-to-server connection. What happens during the TLS handshake, what does a certificate prove, and why cannot a man-in-the-middle intercept the session even if they can read all packets?

Sample answer outline

TLS handshake: client hello (cipher suites), server hello plus certificate, client verifies certificate against trusted CA chain, key exchange (ECDHE), symmetric session key derived from shared secret. Certificate proves the server owns the domain (signed by a CA the OS/browser trusts). MITM cannot derive the session key because ECDHE relies on the discrete log problem; they cannot sign with the server's private key.

Expect these follow-ups

  • What is HSTS and how does it prevent SSL stripping attacks?
  • What is certificate pinning and why is it more common in mobile apps than in web apps?
securityhttpstlsfundamentalsbrowser

As asked

A user reports that a tweet containing emoji is rejected as over the 280-character limit even though the visible character count on the screen shows 279. Explain why this happens and how you would fix the character counting logic.

Sample answer outline

A strong answer explains the difference between Unicode code points, UTF-16 code units, and bytes: emoji outside the BMP (U+1F600 and above) require 2 UTF-16 code units (a surrogate pair), so a JavaScript length check counts them as 2 characters. The fix is to count Unicode code points (spread operator or Array.from in JS, which respects code point boundaries) rather than using string.length. The candidate should also mention that X's weighted tweet length algorithm counts URLs as 23 regardless of actual length, which is a separate but related complexity.

Expect these follow-ups

  • What would happen if you tried to truncate a tweet at exactly 280 characters using string.length and the tweet contained emoji near the cutoff?
  • How does this affect your database storage if you VARCHAR(280) the tweet column?
company:twitter-xunicodeutf-8javascriptencodingtechnical-fundamentals

As asked

Walk me through the stages of a Metal render pipeline from vertex buffer to pixel on screen, and explain where you would put custom compute work if you needed to do physics simulation before rendering.

Sample answer outline

The Metal render pipeline: vertex fetch from vertex buffers, vertex shader (positions and per-vertex data), primitive assembly and rasterization, fragment shader (color and depth per pixel), depth and stencil testing, blending, and framebuffer write. For physics simulation, a Metal compute pass (MTLComputeCommandEncoder) runs before the render pass; it reads from simulation buffers, writes updated positions, and those buffers are then bound as vertex buffers for the render pass. The candidate should mention that compute and render passes are encoded in order on a single MTLCommandBuffer, and that explicit synchronization via MTLFence or resource hazard tracking is needed if the same buffer is written in compute and read in render.

Expect these follow-ups

  • What is the difference between MTLCommandBuffer and MTLCommandQueue?
  • How does tile-based deferred rendering on Apple Silicon affect how you write your fragment shader?
company:applemetalgpuapple-silicongraphics