Frontend Engineer interview questions & answers

20 Frontend Engineer interview questions with complete model answers, spanning Coding, Technical, System design, Behavioral, Product & growth. The bank holds 288 Frontend Engineer questions in total, tagged by round and difficulty.

BehavioralEasyFrontend EngineerSecond interview round

1. What methods do you usually use to learn?

Model answer

  1. Situation — In my previous work, I often had to learn unfamiliar frontend tools while still delivering features on schedule. One example was joining a project where I needed to understand an existing component framework and its conventions before contributing to a user-facing flow. I could not rely on a long onboarding period because the team was actively shipping.
  2. Task — I needed to become productive quickly without learning only enough to make one change. My goal was to understand the underlying model, apply it safely, and retain the knowledge so I could help the team later.
  3. Action
  • I start by clarifying the learning goal and time horizon. For a new library, I identify the two or three capabilities the current feature actually needs rather than trying to read everything.
  • I build a small working example from the official documentation, then compare it with the patterns already used in the codebase. This helps me distinguish framework behavior from local conventions.
  • I learn by applying the concept to a real, low-risk task. For example, when learning a component pattern, I trace its props, events, and state through one existing feature before implementing a small reusable piece.
  • I verify understanding by writing down the key rules and edge cases in a short note, then explain them to a teammate. Questions from the discussion often reveal gaps in my mental model.
  • I use feedback deliberately: code review, tests, and runtime behavior tell me whether I understood the concept, not just whether I copied a working snippet.
  • I revisit the notes when the same topic comes up, updating them with what I learned rather than keeping a collection of untested links.
  1. Result — This approach helps me turn unfamiliar concepts into working knowledge quickly, while keeping the risk of introducing a brittle pattern low. It also makes my learning useful to the team through clearer implementation notes and knowledge sharing. I have learned that the most effective cycle for me is focused reading, hands-on practice, feedback, and then teaching the idea back in my own words.
BehavioralMediumFrontend EngineerHiring Manager

2. Walk me through a frontend problem you owned end to end in production.

Model answer

  1. Situation — I owned the frontend for an investment order flow used by both first-time and returning investors. The existing flow had grown across several releases: validation rules were duplicated, loading states differed by screen, and users could be unsure whether a tap had submitted an order. Because this is a money movement journey, correctness and clear feedback mattered more than simply reducing clicks.
  2. Task — I was responsible for taking the problem from identifying the user-facing failure through implementation, rollout, and production monitoring. I needed to improve confidence and reduce avoidable failures without changing the backend order semantics or delaying a scheduled release.
  3. Action
  • I first combined support tickets, session replays, and frontend/API telemetry. That showed a meaningful cluster of failures around validation and retries, so I defined success as fewer client-side order errors and fewer duplicate submissions, with completion time and crash-free sessions as guardrails.
  • I mapped the flow with design and backend engineers, then agreed on a single source of truth for order status and field validation. I documented the API states and edge cases—slow responses, rejected orders, and app backgrounding—before changing the UI.
  • I extracted shared validation and status components rather than rewriting the whole flow. I added an explicit submitting state, disabled duplicate submission while a request was in flight, and made error messages actionable without clearing valid user input.
  • I added tests for the important transitions and reviewed accessibility: focus behavior, readable errors, and status announcements. I also added telemetry for validation failures and submission outcomes so we could distinguish UI problems from backend rejection.
  • I coordinated a gradual rollout with QA and the product team. I watched the new metrics and support reports, and kept a rollback path available rather than treating release as the finish line.
  1. Result — In the first few weeks, client-side order errors fell by about 25%, duplicate-submit reports dropped, and order completion improved without a regression in crash-free sessions. The work also gave the team reusable components and clearer ownership of order states. I learned to treat production UI work as an end-to-end reliability problem: the best fix is one users can understand, the team can verify, and telemetry can confirm.
BehavioralMediumFrontend EngineerSecond interview round

3. What challenges did you encounter when encapsulating components?

Model answer

  1. Situation — During my internship, I helped encapsulate components for a live-streaming page that combined a player, chat, and merchant product cards. The challenge was that these pieces were reused in different page contexts, but the first version of some components knew too much about the page—for example, they fetched business data internally and made assumptions about layout and playback state.
  2. Task — I needed to make the components reusable without turning them into generic abstractions that were difficult to configure. The key tension was choosing clear ownership: which state belonged to the page, which behavior belonged inside a component, and how to expose changes without coupling consumers to implementation details.
  3. Action
  • I reviewed the call sites and identified the actual variation points before changing the API. For a product card, these were the item data, loading or disabled state, and user actions—not the page’s request logic.
  • I moved data fetching and cross-component coordination to the page layer. The card received explicit props and emitted a focused event such as onProductClick, so it could be tested independently and reused with different data sources.
  • I replaced ambiguous boolean combinations with explicit state where appropriate, and documented defaults and required inputs. This made empty and unavailable states part of the component contract rather than accidental rendering behavior.
  • I kept the API small. I resisted adding options for hypothetical future uses and instead checked existing consumers with the team before expanding the interface.
  • I added tests for the states consumers actually depended on, including missing product data, disabled actions, and repeated user interaction. I also checked that cleanup and subscriptions stayed with the component that created them.
  1. Result — The components became easier to reuse and reason about, and changes to page-level data flow no longer required edits inside presentation components. I learned that encapsulation is not simply hiding code: it is defining a stable contract and placing state with the owner that can enforce its invariants. When I design a component now, I start from its consumers and real variation points rather than trying to predict every possible future use.
BehavioralMediumFrontend EngineerHiring Manager

4. Describe a time you pushed back on a product decision.

Model answer

  1. Situation — At a previous company, I worked on a customer-facing web app where the product team wanted to add a confirmation modal before users could save a partially completed form. The motivation was understandable: support had seen cases where users believed their work was saved when it was not. But the proposed modal appeared on every save, including routine saves, and our users often repeated that action while entering long applications.
  2. Task — I owned the frontend implementation and needed to help reduce mistaken assumptions about saving without adding friction to a high-frequency task. I wanted to challenge the proposed interaction with evidence, not simply argue from personal preference or block the release.
  3. Action
  • I first clarified the underlying problem with the PM and support lead. We found that the issue was not users failing to confirm a save; it was that the existing success state was easy to miss when the network was slow.
  • I brought examples from session recordings and proposed an alternative: an inline save status that moved through “Saving,” “Saved,” and a recoverable error state, with a timestamp. A modal would remain for genuinely destructive actions.
  • I worked with design to prototype both approaches and ran short usability sessions with representative users. Users noticed the persistent status more reliably and could explain whether their work had been saved.
  • I suggested shipping the status behind an experiment, while tracking save-related support contacts, repeat save attempts, completion time, and save failures. That gave the team a reversible way to decide.
  • When the PM worried that the inline state might be overlooked, I adjusted the placement and added an accessible live announcement for screen readers rather than treating visual prominence as the only solution.
  1. Result — We shipped the inline status for routine saves and kept confirmation dialogs for destructive actions. In the following release period, save-related support contacts fell by 22%, while median form completion time improved by 9%; save failure rates did not increase. I learned that effective pushback starts by aligning on the user problem, then offering a testable alternative that respects the product team’s original concern.
CodingEasyFrontend Engineer

5. What are data- attributes good for?

Model answer

data- attributes are a powerful feature in HTML that allow developers to store custom data directly within HTML elements. Here’s a breakdown of their benefits:

  • Custom Data Storage: data- attributes enable the embedding of additional information directly within an element without needing to add extra classes or IDs, which keeps the HTML clean.
  • JavaScript Access: They provide a straightforward way to access this custom data using JavaScript, making it easy to manipulate or retrieve values dynamically.
  • Separation of Concerns: By using data- attributes, developers can maintain a clear separation between HTML structure, CSS styling, and JavaScript functionality, enhancing maintainability.
  • No Impact on Presentation: These attributes do not interfere with the presentation or functionality of the page, ensuring that they can be used without affecting the user experience.

Example Usage

Here’s an example of how to utilize data- attributes in HTML and access them via JavaScript:

<div id="product" data-product-id="12345" data-category="electronics">
    Product Name
</div>

<script>
    // Accessing the data attributes using JavaScript
    const productElement = document.getElementById('product');
    const productId = productElement.dataset.productId; // "12345"
    const category = productElement.dataset.category; // "electronics"

    console.log(`Product ID: ${productId}, Category: ${category}`);
</script>
  • Accessing Data: The dataset property in JavaScript allows for easy retrieval of the data- attributes.
  • Dynamic Manipulation: This data can be used to dynamically change content or behavior based on user interactions.

Complexity: O(1) time for accessing data attributes; O(n) for manipulation if iterating through multiple elements.

CodingEasyFrontend Engineer

6. Implement utilities to determine non-primitive variable types in JavaScript.

Model answer

// Utility function to determine if a variable is an object
function isObject(variable) {
  return variable !== null && typeof variable === 'object' && !Array.isArray(variable);
}

// Utility function to determine if a variable is an array
function isArray(variable) {
  return Array.isArray(variable);
}

// Utility function to determine if a variable is a function
function isFunction(variable) {
  return typeof variable === 'function';
}

// Utility function to determine if a variable is a date
function isDate(variable) {
  return variable instanceof Date;
}

// Utility function to determine if a variable is a regular expression
function isRegExp(variable) {
  return variable instanceof RegExp;
}

// Example usage:
const exampleObject = {};
const exampleArray = [];
const exampleFunction = function() {};
const exampleDate = new Date();
const exampleRegExp = /abc/;

console.log(isObject(exampleObject)); // true
console.log(isArray(exampleArray)); // true
console.log(isFunction(exampleFunction)); // true
console.log(isDate(exampleDate)); // true
console.log(isRegExp(exampleRegExp)); // true
  • Approach:
  • Use typeof for basic type checks, such as for functions.
  • Use Array.isArray() to check for arrays.
  • Use instanceof to check for specific object types like Date and RegExp.
  • Ensure the input is not null when checking for objects, as typeof null returns 'object'.

Complexity:

  • Time: O(1) for each utility function, as they perform basic type checks.
  • Space: O(1), as no additional data structures are used.
CodingEasyFrontend Engineer

7. Implement the Array.prototype.reduce() method.

Model answer

/**
 * Custom implementation of Array.prototype.reduce()
 * @param {Function} reducer - Function to execute on each element in the array
 * @param {any} initialValue - Value to use as the first argument to the first call of the reducer
 * @returns {any} - The single value that results from the reduction
 */
Array.prototype.myReduce = function(reducer, initialValue) {
    // Check if the array is empty
    if (this.length === 0 && initialValue === undefined) {
        throw new TypeError('Reduce of empty array with no initial value');
    }

    // Initialize accumulator
    let accumulator = initialValue;
    let startIndex = 0;

    // If no initial value, set accumulator to the first element
    if (accumulator === undefined) {
        accumulator = this[0];
        startIndex = 1; // Start from the second element
    }

    // Iterate through the array
    for (let i = startIndex; i < this.length; i++) {
        // Apply the reducer function
        accumulator = reducer(accumulator, this[i], i, this);
    }

    return accumulator;
};

// Example usage:
const numbers = [1, 2, 3, 4];
const sum = numbers.myReduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 10
  • The method checks for an empty array and handles initial values appropriately.
  • It iterates through the array, applying the reducer function to accumulate a result.
  • The final accumulated value is returned after processing all elements.

Complexity: time O(n), space O(1)

CodingEasyFrontend Engineer

8. Implement the Array.prototype.reduce() method.

Model answer

// Implementing the Array.prototype.reduce() method
Array.prototype.myReduce = function(callback, initialValue) {
  // Check if the array is empty and no initial value is provided
  if (this.length === 0 && initialValue === undefined) {
    throw new TypeError('Reduce of empty array with no initial value');
  }

  let accumulator = initialValue;
  let startIndex = 0;

  // If no initial value is provided, use the first element of the array
  if (accumulator === undefined) {
    accumulator = this[0];
    startIndex = 1;
  }

  // Iterate over the array elements
  for (let i = startIndex; i < this.length; i++) {
    accumulator = callback(accumulator, this[i], i, this);
  }

  return accumulator;
};

// Example usage:
const numbers = [1, 2, 3, 4];
const sum = numbers.myReduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 10
  • The myReduce function starts by checking if the array is empty and no initial value is provided, throwing a TypeError if so.
  • If an initial value is provided, it sets the accumulator to this value; otherwise, it uses the first element of the array.
  • It iterates over the array, applying the callback function to the accumulator and each element.
  • Finally, it returns the accumulated result.

Complexity:

  • Time: O(n), where n is the number of elements in the array, as each element is processed once.
  • Space: O(1), as it uses a constant amount of space for the accumulator.
Product & growthMediumFrontend EngineerHiring Manager

9. How do you decide when to refactor versus ship?

Model answer

Clarify & scope

I treat refactor versus ship as a risk-and-value decision, not a preference for clean code or speed. First I clarify what the deadline protects, what user outcome the change delivers, and whether the existing code creates a correctness, reliability, or delivery risk. In a financial app, a defect in order placement or displayed balances has a much higher cost than a minor visual inconsistency.

User segments & pain points

I identify who bears the cost of the current code. Users may experience crashes, incorrect states, slow screens, or confusing errors; engineers may be slowed by fragile code, making every future feature riskier. I also ask whether this is a high-change area, such as an order flow, or stable code that is unlikely to be touched again.

Goals & success metrics

The goal is to deliver the user value safely while preserving the ability to make future changes. I look at release impact, defect and rollback risk, cycle time, test coverage of critical behavior, and the expected cost of carrying the debt. I set guardrails around correctness, crash-free sessions, and the committed delivery date.

Solutions

I usually consider three choices: ship the smallest safe change; do a targeted refactor around the risky boundary; or defer the feature for a broader refactor. Recommendation: Prefer the smallest safe change plus a focused refactor when the current structure makes the feature unsafe or repeatedly expensive. I avoid broad rewrites unless evidence shows that incremental changes cannot address the risk.

Prioritization & trade-offs

I compare the cost of refactoring now with the likely cost of bugs and slower follow-on work. I refactor before shipping when the code prevents us from proving critical behavior, creates material production risk, or makes the requested change disproportionately expensive. I ship first when the change is low-risk, reversible, and time-sensitive, while documenting debt and creating a specific follow-up owner and milestone. I make that trade-off visible to product, design, and backend partners rather than silently borrowing quality.

MVP, measurement & rollout

I keep the scope bounded: tests around the risky behavior, a small seam or component extraction, and no unrelated cleanup. I use code review, automated tests, and a staged or feature-flagged rollout where available. After release, I check the agreed guardrails and the follow-up work’s actual cost. If the debt is not creating measurable risk or friction, I do not refactor merely for aesthetics; if it is, I prioritize it with evidence.

Product & growthMediumFrontend EngineerSecond interview round

10. How do you evaluate the results after optimizing a page?

Model answer

Clarify & scope

I’d first confirm what “optimized” means for this page: faster loading, better task completion, or both. I’d compare the new version with a representative baseline, keeping the page’s content, traffic mix, and measurement window comparable. For a Meituan page, such as a restaurant listing, I’d care about both the customer experience and downstream actions like opening a restaurant or placing an order.

User segments & pain points

I’d segment by device, network quality, app or browser entry point, city, and new versus returning users. Averages can hide a regression—for example, a page may improve on Wi-Fi but get slower on lower-end Android devices or weak mobile networks.

Goals & success metrics

My North Star would be the page’s intended user outcome, such as successful restaurant-detail visits or orders per eligible session. I’d pair that with frontend measures: real-user p75 LCP, INP, and CLS; error rate; and abandonment. I’d also watch guardrails such as API failures, image quality, and conversion, so a faster page that harms usability is not called a success.

Solutions

I’d measure before and after using both field data and controlled lab tests. Field data tells me what customers actually experience; lab tests help reproduce and diagnose regressions. For a release behind an experiment, I’d compare treatment and control with consistent eligibility and attribution, and check that the change—not a traffic or campaign shift—explains the result.

flowchart LR
  A[Set baseline] --> B[Ship to experiment]
  B --> C[Measure user outcomes]
  B --> D[Measure performance]
  C --> E[Check segments and guardrails]
  D --> E
  E --> F{Improved safely?}
  F -->|Yes| G[Expand rollout]
  F -->|No| H[Investigate or roll back]
Diagram

Prioritization & trade-offs

I’d prioritize changes that improve a user-visible bottleneck and have a measurable impact. For example, reducing above-the-fold image weight is usually preferable to optimizing a rarely used interaction. I’d make the trade-off explicit if an optimization saves time but increases maintenance complexity or reduces visual quality.

MVP, measurement & rollout

I’d define the hypothesis, primary metric, guardrails, sample size, and decision window before launch. I’d release to a small percentage, inspect both aggregate and segment results, then expand gradually if the improvement is statistically credible and guardrails remain healthy. I’d also verify the result after full rollout and document the baseline, change, and observed impact.

Product & growthMediumFrontend EngineerHiring Manager

11. What would you change in the Groww app?

Model answer

Clarify & scope

I would improve the moment when a user tries to understand whether their investments are doing well. I’d focus on the portfolio overview, not add another trading feature: it is a frequent destination, and a clearer explanation can help users make informed decisions without encouraging unnecessary trades.

User segments & pain points

My primary segment is a newer investor who owns a few mutual funds or stocks but does not yet understand the difference between invested amount, current value, and returns. A single green or red number can be misleading: it may represent today’s movement, total profit and loss, or an annualized return, and users may not know which.

Goals & success metrics

The North Star would be the percentage of portfolio visitors who can correctly understand their portfolio’s value and return. In practice, I’d use a short research task to measure comprehension, alongside repeat portfolio visits and usage of return breakdowns. Guardrails would include support contacts about portfolio values, time to find a holding, page performance, and no increase in impulsive order activity.

Solutions

I’d explore three options: clearer labels and tooltips; a compact breakdown of invested amount, current value, and absolute return; and a time-range chart with a clear explanation of the selected period. I would test the terminology with both new and experienced investors before choosing a visual design.

Recommendation: Start with the labeled value-and-return breakdown, then add the time-range chart only if research shows it resolves a remaining user question. It addresses the core ambiguity with less visual complexity and lower implementation risk.

Prioritization & trade-offs

I’d prioritize by user impact, reach, confidence, and effort. Labels and a breakdown are likely to have broad reach and modest effort; a sophisticated chart has higher engineering and data-validation cost. I would not trade accurate, consistent numbers across screens for a more polished visualization. All calculations and definitions should match the underlying portfolio data and be reviewed with the relevant domain owners.

MVP, measurement & rollout

I’d prototype the language, validate comprehension in usability sessions, then release the change to a small cohort behind a feature flag. I’d compare the primary metric and guardrails against a control, check for differences between new and experienced users, and expand only if users understand the numbers better without performance or trust regressions. I’d use support feedback and event data to decide whether the chart belongs in a later iteration.

Product & growthMediumFrontend EngineerHiring Manager

12. What would you change about Groww's web experience right now?

Model answer

Clarify & scope

I wouldn’t start by assuming the web experience is broken. I’d first look at funnel data, support contacts, and usability sessions to identify the biggest user problem. My initial hypothesis would be that newer investors can find a product, but may have difficulty understanding what they own, what changed, and what action—if any—they should take. I’d focus on the signed-in investing experience, not redesign the whole site.

User segments & pain points

I’d prioritize first-time and occasional investors. They need confidence and clear explanations, while experienced users often value speed, compact information, and control. A dense dashboard can serve the latter but overwhelm the former; a simplified dashboard can do the reverse.

Goals & success metrics

The North Star would be the share of users who successfully complete an intended investing task—such as reviewing a holding or placing an order—without needing support. I’d pair that with task-completion time and user-reported confidence. Guardrails: order errors, accidental or rapidly reversed orders, support contacts, page performance, and accessibility. I would not optimize for more trades alone; that can reward unnecessary activity.

Solutions

  1. Make the portfolio’s total value, day change, and longer-term performance easy to distinguish, with clear time ranges and plain-language definitions.
  2. Give each holding a consistent detail view: position, relevant performance period, key risks or disclosures, and available actions—without implying a recommendation.
  3. Improve responsive behavior, keyboard navigation, loading feedback, and error recovery across the research-to-order journey.

Recommendation: Start with a usability-led portfolio clarity improvement. It addresses a high-frequency task, is measurable, and can be delivered without changing the underlying investment decision or order flow.

flowchart LR
  A[Open portfolio] --> B[Understand value and change]
  B --> C[Review a holding]
  C --> D{Choose an action}
  D --> E[View details]
  D --> F[Continue to order]
Diagram

Prioritization & trade-offs

I’d rank work by user impact, confidence from research, and implementation effort. Clear labels and time-range explanations are likely lower effort than a broad dashboard redesign, so I’d test those first. I’d preserve a fast path for experienced users and avoid adding educational content that pushes important actions below the fold.

MVP, measurement & rollout

I’d prototype the changes, test key tasks with new and experienced investors, then run an instrumented experiment on a limited cohort. I’d compare task completion, comprehension, and guardrails against the existing experience, segmenting by device and user tenure. If clarity improves without harming speed or safety, I’d expand gradually; otherwise, I’d use session findings to revise the design before rollout.

System designMediumFrontend Engineer

13. Can you explain any common techniques or recent issues solved in regards to front-end security?

Model answer

1. Requirements & scale

  • Functional Requirements:
  • Protect user data from unauthorized access.
  • Ensure integrity and confidentiality of data in transit and at rest.
  • Provide mechanisms for authentication and authorization.
  • Non-functional Requirements:
  • High availability and low latency.
  • Scalability to handle up to 10,000 concurrent users.
  • Compliance with security standards like OWASP.
  • Estimates:
  • QPS: Assume 100 QPS for authentication requests.
  • Storage: 1GB for user credentials and session data.
  • Bandwidth: 10 Mbps for secure data transmission.

2. High-level architecture

graph TD
  subgraph Client
    A["Browser"]
  end
  subgraph "Edge/CDN"
    B["WAF"]
  end
  subgraph "Load Balancer"
    C["LB"]
  end
  subgraph "API / Services"
    D["Auth Service"]
    E["Data Service"]
  end
  subgraph "Datastores"
    F["SQL DB"]
    G["Cache"]
  end
  A -->|"HTTPS Request"| B
  B -->|"Filtered Request"| C
  C -->|"Route Request"| D
  D -->|"Auth Token"| E
  E -->|"Data Query"| F
  E -->|"Cache Lookup"| G
Diagram

3. API design

  • POST /api/auth/login: Authenticate user and return token.
  • GET /api/data: Retrieve user data, requires auth token.
  • POST /api/auth/logout: Invalidate user session.

4. Data model & storage

  • Datastore: SQL DB for user credentials, NoSQL for session tokens.
  • Tables:
  • Users: id, username, password_hash, salt.
  • Sessions: token, user_id, expires_at.
  • Partition Key: user_id for sharding user data.

5. Deep dive

A common front-end security technique is implementing Content Security Policy (CSP) to mitigate XSS attacks.

sequenceDiagram
  participant Browser
  participant Server
  Browser->>Server: Request with CSP header
  Server->>Browser: Response with CSP
  Browser->>Browser: Enforce CSP on resources
Diagram
  • CSP Headers: Define allowed sources for scripts, styles, and other resources.
  • Nonce-based CSP: Generate a unique nonce for each request to allow specific inline scripts.

6. Scale, bottlenecks & trade-offs

  • Replication: Use database replication for high availability.
  • Sharding: Partition user data by user_id to distribute load.
  • Caching: Implement caching for frequently accessed data.
  • Trade-offs:
  • Consistency vs. Availability: Choose eventual consistency for user session data.
  • Security vs. Performance: Implement CSP without affecting page load time significantly.
  • SQL vs. NoSQL: Use SQL for structured user data, NoSQL for flexible session storage.
System designMediumFrontend Engineer

14. What is Flash of Unstyled Content?

The full question

What is Flash of Unstyled Content? How do you avoid FOUC?

Model answer

1. Requirements & scale

  • Functional Requirements:
  • Ensure consistent styling across all pages.
  • Minimize the occurrence of Flash of Unstyled Content (FOUC).
  • Non-Functional Requirements:
  • Fast page load times.
  • High availability and responsiveness.
  • Scale Estimates:
  • Assume 1 million page views per day.
  • Average page size is 1MB, with CSS files being around 50KB.
  • Bandwidth: 1 million * 1MB = ~1TB/day.

2. High-level architecture

graph TD
  subgraph Client
    A[Browser]
  end
  subgraph Edge/CDN
    B[CDN]
  end
  subgraph Load Balancer
    C[Load Balancer]
  end
  subgraph API / Services
    D[Web Server]
  end
  subgraph Cache
    E[Cache Server]
  end
  subgraph Datastores
    F[Database]
  end
  A -->|"Request HTML/CSS"| B
  B -->|"Cached HTML/CSS"| A
  B -->|"Cache Miss"| C
  C -->|"Forward Request"| D
  D -->|"Fetch Data"| F
  F -->|"Return Data"| D
  D -->|"Render HTML"| E
  E -->|"Cache HTML/CSS"| B
Diagram

3. API design

  • GET /styles/main.css: Serve the main CSS file.
  • GET /scripts/main.js: Serve the main JavaScript file.
  • GET /page: Serve the HTML content of a page.

4. Data model & storage

  • Datastore: Use a CDN for static assets like CSS and JavaScript to reduce latency and bandwidth.
  • Cache: Implement caching strategies at the CDN and browser levels to store CSS files.

5. Deep dive

To avoid FOUC, the main strategy is to ensure that CSS is loaded and applied before any content is rendered. This involves:

  • Inlining Critical CSS: Extract and inline the CSS necessary for above-the-fold content directly into the HTML document.
  • Asynchronous Loading of Non-Critical CSS: Load non-critical CSS files asynchronously using JavaScript.
sequenceDiagram
    participant Browser
    participant CDN
    participant Server
    Browser->>CDN: Request HTML
    CDN-->>Browser: Return HTML with inlined CSS
    Browser->>CDN: Request additional CSS
    CDN-->>Browser: Return CSS
    Browser->>Server: Request additional resources
    Server-->>Browser: Return resources
Diagram

6. Scale, bottlenecks & trade-offs

  • Caching: Leverage browser and CDN caching to reduce load times and prevent FOUC.
  • Single Points of Failure: Ensure CDN has redundancy to handle failures.
  • Trade-offs:
  • Consistency vs. Performance: Inlining CSS improves initial render but increases HTML size.
  • Complexity vs. Maintainability: Managing critical CSS can be complex but is necessary for optimal performance.

By inlining critical CSS and utilizing caching effectively, we can significantly reduce the occurrence of FOUC while maintaining fast load times and a responsive user experience.

System designMediumFrontend Engineer

15. Can you describe your workflow when you create a web page?

Model answer

1. Requirements & scale

  • Functional Requirements:
  • Design a responsive web page.
  • Ensure cross-browser compatibility.
  • Implement interactive elements using JavaScript.
  • Non-functional Requirements:
  • Optimize for fast load times.
  • Ensure accessibility standards are met.
  • Scale:
  • Assume the page will be accessed by up to 10,000 users daily.
  • Average page size: 2MB.
  • Bandwidth: 10,000 users x 2MB = 20GB/day.

2. High-level architecture

flowchart TD
  subgraph Client
    A[Browser]
  end
  subgraph "Edge/CDN"
    B[CDN]
  end
  subgraph "Load Balancer"
    C[Load Balancer]
  end
  subgraph "API / Services"
    D[Web Server]
  end
  subgraph "Cache"
    E[Cache Layer]
  end
  subgraph "Datastores"
    F[Database]
  end

  A -->|HTTP Request| B
  B -->|Cached Content| A
  B -->|Miss| C
  C -->|Forward Request| D
  D -->|Fetch Data| E
  E -->|Cache Miss| F
  F -->|Data| E
  E -->|Cached Data| D
  D -->|Response| C
  C -->|Response| B
  B -->|HTTP Response| A
Diagram

3. API design

  • GET /api/content: Fetch content for the web page.
  • POST /api/feedback: Submit user feedback.

4. Data model & storage

  • Datastore: SQL database for structured data.
  • Key Tables:
  • Content: Stores HTML, CSS, JavaScript files.
  • Feedback: Stores user feedback.

5. Deep dive

  • Responsive Design:
  • Use CSS Flexbox/Grid for layout.
  • Media queries for different screen sizes.
  • Accessibility:
  • Use semantic HTML tags.
  • Implement ARIA roles and properties.
sequenceDiagram
  participant User
  participant Browser
  participant CDN
  participant Server
  participant Database

  User->>Browser: Request Page
  Browser->>CDN: Fetch Resources
  CDN-->>Browser: Cached Resources
  CDN->>Server: Request Dynamic Content
  Server->>Database: Query Data
  Database-->>Server: Return Data
  Server-->>CDN: Cache Response
  CDN-->>Browser: Return Content
  Browser-->>User: Display Page
Diagram

6. Scale, bottlenecks & trade-offs

  • Caching: Use CDN for static assets; cache dynamic content at the server.
  • Sharding: Not needed at this scale, but consider for future growth.
  • Trade-offs:
  • Consistency vs. Availability: Favor availability for faster user experience.
  • Push vs. Pull: Use pull for dynamic content updates.
  • Single Points of Failure: Mitigate by using multiple CDN nodes and load balancers.
System designMediumFrontend Engineer

16. Can you describe the difference between progressive enhancement and graceful degradation?

Model answer

Progressive Enhancement

Progressive enhancement is a strategy for web design that focuses on ensuring a basic level of user experience for all users, regardless of their browser capabilities, while providing an enhanced experience for users with more advanced browsers. The approach starts with a strong foundation of core content and functionality, and then layers on additional features and improvements as the user's browser capabilities allow.

  • Core Content First: Begin with a basic version of the website that works on all browsers, focusing on essential content and functionality.
  • Enhancements: Add improvements such as JavaScript or CSS3 features that enhance the user experience for browsers that support them.
  • User Experience: Ensures that all users can access the core content, but those with modern browsers have a richer experience.

Graceful Degradation

Graceful degradation takes the opposite approach by designing a site for modern, fully-capable browsers first, and then ensuring that it still functions in older or less capable browsers, albeit with a reduced experience.

  • Full Experience First: Design the site with all features for modern browsers.
  • Fallbacks: Implement fallbacks or alternative solutions for older browsers to ensure basic functionality.
  • User Experience: Users with modern browsers get the full experience, while those with older browsers receive a simplified version.

Key Differences

  • Starting Point: Progressive enhancement starts with a basic version and adds features, while graceful degradation starts with a full-featured version and scales back.
  • User Experience: Progressive enhancement ensures all users have access to core content, while graceful degradation focuses on providing a full experience to users with modern browsers.
  • Development Approach: Progressive enhancement often leads to more robust and accessible websites, as it prioritizes content and functionality from the start.

Conclusion

Both strategies aim to improve user experience across different browsers and devices, but they take different paths to achieve this goal. Progressive enhancement is often preferred for its focus on accessibility and content-first design, while graceful degradation is useful when targeting modern browsers with a focus on cutting-edge features.

TechnicalEasyFrontend EngineerRound 3: Platform round

17. What are JavaScript best practices?

Model answer

  1. Write clear, maintainable code. Use descriptive names, small functions with focused responsibilities, and consistent formatting. Prefer straightforward code over clever shortcuts.
  2. Use modern JavaScript deliberately. Use const by default and let when reassignment is needed; avoid var. Prefer modules, async/await, and well-understood built-in APIs. Choose immutable transformations when they make state changes easier to reason about.
  3. Handle failures and edge cases. Validate inputs at system boundaries, handle rejected promises, and provide useful errors. Avoid swallowing exceptions or returning misleading fallback values.
  4. Avoid shared-state surprises. Keep state local where possible, avoid unintended mutation, and be cautious with closures, this, and asynchronous work that can finish out of order.
  5. Treat security as part of correctness. Do not inject untrusted content with innerHTML; escape or sanitize data for its output context. Avoid exposing secrets, and use safe APIs for browser storage and network requests.
  6. Test behavior, not implementation details. Cover normal cases, boundaries, and failures. For frontend code, test accessibility and user interactions as well as rendering.
  7. Keep performance measurable. Choose suitable data structures, avoid unnecessary work in render paths, and profile before optimizing. For example, debounce expensive search requests and cancel or ignore stale responses.
  8. Use tooling and team conventions. Apply linting, formatting, type checking where appropriate, code review, and dependency updates. Keep APIs and browser compatibility explicit rather than relying on accidental behavior.
TechnicalEasyFrontend EngineerFirst interview round

18. What are the advantages of Promises, and what problems do they solve?

Model answer

Promises represent the eventual result of an asynchronous operation: either a value or an error. They solve several problems common with callbacks:

  1. Flattening nested async code: Returning a promise from .then() chains the next operation, rather than nesting callbacks inside callbacks.
  2. Consistent error propagation: A rejection travels down the chain until a .catch() handles it. This makes errors from multiple async steps easier to manage in one place.
  3. Composition: Promise.all, Promise.allSettled, Promise.race, and Promise.any express common coordination patterns clearly. For example, Promise.all is useful when independent data requests must all finish before rendering a page.
  4. Interoperability: APIs that return promises have a consistent interface and can be consumed with either .then() or async/await.

A promise has three states: pending, fulfilled, or rejected. Once settled, its state and result do not change. That makes completion easier to reason about than callbacks that may be invoked inconsistently.

flowchart LR
  A[Pending] -->|resolve value| B[Fulfilled]
  A -->|reject error| C[Rejected]
  B --> D[then handler]
  C --> E[catch handler]
Diagram

Promises do not automatically provide cancellation, retries, or concurrency limits. For example, Promise.race can stop waiting for a slow request, but does not stop the underlying network operation. Those concerns need explicit mechanisms such as AbortController for fetch cancellation or a queue for limiting concurrency.

TechnicalEasyFrontend EngineerFirst Round

19. What do the HTTP response-code ranges 1xx, 2xx, 3xx, 4xx, and 5xx represent, and what do status codes 501 and 502 mean?

Model answer

HTTP status codes are grouped by their first digit:

  • 1xx — Informational: The request was received and processing is continuing. For example, 100 Continue lets a client proceed with sending a request body.
  • 2xx — Success: The request was successfully received, understood, and handled. Common examples are 200 OK, 201 Created, and 204 No Content.
  • 3xx — Redirection: The client needs to take further action, often by using another URL. Examples include 301 Moved Permanently and 302 Found.
  • 4xx — Client error: The request cannot be completed because of something attributable to the client, such as invalid input, missing credentials, or a nonexistent resource. Examples are 400, 401, 403, and 404.
  • 5xx — Server error: The server failed to fulfill an otherwise valid request, often due to an internal failure or an unavailable dependency. Examples include 500, 502, and 503.

Specifically:

  • 501 Not Implemented: The server does not support the functionality required to fulfill the request. It is commonly used when the server does not recognize or implement a request method or capability.
  • 502 Bad Gateway: A server acting as a gateway or proxy received an invalid response from an upstream server. For example, a frontend-facing API gateway might return 502 if a service it called responded incorrectly or the connection failed.

The key distinction is that 501 describes an unsupported server capability, while 502 describes a failure in communication with an upstream server.

TechnicalEasyFrontend EngineerFirst Round

20. What React Hooks have you used?

Model answer

I’ve used these Hooks most often:

  • useState — local UI state such as selected tabs, form values, and whether a menu is open.
  • useEffect — synchronize with external systems, such as adding event listeners, updating the document title, or subscribing to a data source. I avoid using it to derive values that can be computed during render.
  • useContext — read shared values such as theme, locale, or authenticated-user context without passing props through every level.
  • useRef — hold a DOM node or a mutable value that should persist across renders without triggering a render.
  • useMemo and useCallback — cache an expensive calculation or a function when profiling shows that referential stability helps avoid unnecessary work. I don’t add them automatically.
  • useReducer — manage state with related transitions, for example a multi-step form or a component with several interaction states.
  • useLayoutEffect — make a DOM measurement or visual adjustment before the browser paints, when a visible intermediate frame would be a problem. I use it sparingly because it can block painting.
  • Custom Hooks — package reusable stateful behavior, such as media-query handling or subscription logic, while following the Rules of Hooks.

For example, in a feed UI, I might use state for the selected filter, refs for a video element, and an effect to subscribe to visibility changes. I’d keep feed data fetching and caching in the app’s established data layer rather than adding ad hoc effects to every component.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions