Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save carefree-ladka/e7475bccc9631f677fa455383e4b7fff to your computer and use it in GitHub Desktop.

Select an option

Save carefree-ladka/e7475bccc9631f677fa455383e4b7fff to your computer and use it in GitHub Desktop.
Frontend Interview Preparation Guide 2026

Frontend Interview Preparation Guide 2026


1. Core JavaScript

1.1 Language Fundamentals

Variable Declarations

  • let / const / var
    • Block scope vs function scope
    • Temporal Dead Zone (TDZ)
    • Hoisting behavior
    • When to use each
    • const with objects/arrays (reference immutability)

Data Types

  • Primitive Types

    • string, number, boolean, null, undefined, symbol, bigint
    • Immutability of primitives
    • Symbol use cases (unique keys, well-known symbols)
    • BigInt for large integers
  • Reference Types

    • Objects, Arrays, Functions
    • Shallow vs deep copy
    • Pass-by-value vs pass-by-reference

Type Coercion

  • Equality Operators

    • == vs ===
    • Object.is() differences
    • Implicit coercion rules
    • Truthy/Falsy values
  • Special Values

    • NaN (Not-a-Number)
    • null vs undefined
    • typeof operator quirks
    • isNaN() vs Number.isNaN()

Operators

  • Logical operators

    • Short-circuit evaluation
    • Nullish coalescing (??)
    • Optional chaining (?.)
    • Logical assignment (&&=, ||=, ??=)
  • Spread & Rest

    • Array/object spreading
    • Rest parameters
    • Destructuring with rest

1.2 Execution Model & Runtime

Call Stack

  • Stack frames
  • Stack overflow
  • Recursion limits
  • Call stack visualization

Event Loop

  • Phases

    • Call stack
    • Web APIs / Node APIs
    • Callback queue
    • Microtask queue
    • Rendering
  • Task Queues

    • Macrotasks (setTimeout, setInterval, I/O)
    • Microtasks (Promises, queueMicrotask, MutationObserver)
    • Priority: Microtasks execute before macrotasks
    • process.nextTick() (Node.js)
  • Common Pitfalls

    • Starvation (infinite microtasks)
    • Blocking the event loop
    • Long-running synchronous operations

Hoisting

  • Variable hoisting (var vs let/const)
  • Function hoisting (declarations vs expressions)
  • Class hoisting
  • Temporal Dead Zone with let/const

1.3 Functions & Scope

Function Types

  • Function Declarations

    function foo() {}
  • Function Expressions

    const foo = function() {}
  • Arrow Functions

    const foo = () => {}

Arrow vs Regular Functions

  • this binding differences
  • No arguments object in arrow functions
  • Cannot be used as constructors
  • Implicit return for single expressions
  • No prototype property

this Binding

  • Four binding rules

    1. Default binding (global/undefined in strict mode)
    2. Implicit binding (method invocation)
    3. Explicit binding (call/apply/bind)
    4. new binding (constructor)
  • Precedence: new > explicit > implicit > default

  • Arrow function behavior: Lexical this

Function Methods

  • call(thisArg, ...args): Invoke immediately
  • apply(thisArg, [args]): Invoke with array of args
  • bind(thisArg, ...args): Return new function with bound this

Currying

  • Transform f(a, b, c)f(a)(b)(c)
  • Partial application
  • Use cases: Configuration, composition
  • Implementation:
    function curry(fn) {
      return function curried(...args) {
        if (args.length >= fn.length) {
          return fn.apply(this, args);
        }
        return (...nextArgs) => curried(...args, ...nextArgs);
      };
    }

Partial Application

  • Pre-fill some arguments
  • Different from currying
  • Use cases: Reusable utilities

Closures

  • Definition: Function + lexical environment

  • Use cases

    • Data privacy
    • Function factories
    • Callbacks maintaining state
    • Memoization
    • Module pattern
  • Memory implications

  • Common interview questions

    • Loop with closures
    • Private variables
    • Counter implementations

1.4 Objects & Arrays

Object Operations

  • Creation

    • Object literals
    • Object.create()
    • Constructor functions
    • Classes
  • Property access

    • Dot notation vs bracket notation
    • Dynamic property names
    • Computed property names
  • Methods

    • Object.keys() / Object.values() / Object.entries()
    • Object.assign() (shallow copy)
    • Object.freeze() (immutable, shallow)
    • Object.seal() (prevent add/delete)
    • Object.preventExtensions()
    • Object.hasOwn() vs hasOwnProperty()
    • Object.getOwnPropertyDescriptors()

Shallow vs Deep Copy

  • Shallow copy

    • Spread operator: { ...obj }
    • Object.assign()
    • Array.slice()
  • Deep copy

    • structuredClone() (modern, recommended)
    • JSON.parse/stringify (limitations)
    • Recursive manual implementation
    • Libraries: lodash cloneDeep

Collections

  • Map

    • Key-value pairs (any type as key)
    • Maintains insertion order
    • Size property
    • Methods: set, get, has, delete, clear
  • Set

    • Unique values
    • Methods: add, has, delete, clear
    • Use cases: Deduplication, membership checks
  • WeakMap

    • Keys must be objects
    • No enumeration
    • Garbage collection friendly
    • Use case: Private data
  • WeakSet

    • Objects only
    • No enumeration
    • Use case: Tracking object references

Destructuring

  • Objects

    const { name, age, city = 'Unknown' } = person;
    const { name: fullName } = person; // Rename
  • Arrays

    const [first, second, ...rest] = array;
    const [, , third] = array; // Skip
  • Nested destructuring

  • Function parameters

Spread & Rest

  • Spread (...)

    • Arrays: [...arr1, ...arr2]
    • Objects: { ...obj1, ...obj2 }
    • Function arguments: fn(...args)
  • Rest (...)

    • Function parameters: function fn(...args) {}
    • Destructuring: const [first, ...rest] = arr

1.5 Advanced Patterns

Debounce

  • Purpose: Delay execution until after wait time with no calls
  • Use cases: Search input, window resize
  • Implementation:
    function debounce(fn, delay) {
      let timeoutId;
      return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn.apply(this, args), delay);
      };
    }
  • Leading vs trailing edge

Throttle

  • Purpose: Execute at most once per time period
  • Use cases: Scroll events, button clicks
  • Implementation:
    function throttle(fn, limit) {
      let inThrottle;
      return function(...args) {
        if (!inThrottle) {
          fn.apply(this, args);
          inThrottle = true;
          setTimeout(() => inThrottle = false, limit);
        }
      };
    }
  • Leading vs trailing edge

Polyfills

  • Must know:

    • Array.prototype.map
    • Array.prototype.filter
    • Array.prototype.reduce
    • Function.prototype.bind
    • Promise
    • Promise.all
    • Promise.allSettled
    • Array.prototype.flat
    • Object.create
  • Implementation approach

    • Check if method exists
    • Add to prototype
    • Handle edge cases

1.6 Memory Management

Memory Leaks

  • Common causes

    • Global variables
    • Forgotten timers/intervals
    • Event listeners not removed
    • Closures holding references
    • Detached DOM nodes
    • Console.log in production
  • Detection

    • Chrome DevTools Memory profiler
    • Heap snapshots
    • Allocation timeline
  • Prevention

    • Clean up event listeners
    • Clear timers/intervals
    • WeakMap/WeakSet for caching
    • Proper component unmounting (React)

Garbage Collection

  • Mark-and-sweep algorithm
  • Reference counting
  • Generational collection
  • When GC runs (unpredictable)
  • Performance impact

1.7 Prototypes & Inheritance

Prototype Chain

  • Every object has [[Prototype]]
  • __proto__ vs prototype
  • Object.getPrototypeOf()
  • Object.setPrototypeOf()
  • Prototype chain lookup

Inheritance

  • Prototypal inheritance

    const parent = { greet() { console.log('Hi'); } };
    const child = Object.create(parent);
  • Constructor functions

    function Person(name) { this.name = name; }
    Person.prototype.greet = function() {};
  • ES6 Classes

    class Person extends Animal {
      constructor(name) {
        super();
        this.name = name;
      }
    }
  • Class features

    • Private fields (#field)
    • Static methods/properties
    • Getters/setters
    • super keyword

2. Asynchronous JavaScript

2.1 Promises

Promise States

  • Pending (initial)
  • Fulfilled (resolved)
  • Rejected (error)
  • Settled (fulfilled or rejected)

Promise API

  • Constructor

    new Promise((resolve, reject) => {
      // async operation
    })
  • Methods

    • .then(onFulfilled, onRejected)
    • .catch(onRejected)
    • .finally(onFinally)

Promise Chaining

  • Return values propagate
  • Return promise for async chaining
  • Error propagation through chain
  • Implicit try-catch in .then

Error Handling

  • .catch() at end of chain
  • .then(null, errorHandler)
  • Uncaught promise rejections
  • window.addEventListener('unhandledrejection')

2.2 Async/Await

Syntax

async function fetchData() {
  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

Key Points

  • async function always returns Promise
  • await pauses execution
  • Can only use await inside async functions (or top-level modules)
  • Error handling with try-catch
  • Top-level await (ES2022)

Async vs Promises

  • Cleaner syntax
  • Better error handling
  • Easier debugging
  • Sequential vs parallel execution

2.3 Promise Combinators

Promise.all([promises])

  • Waits for all to resolve
  • Fails fast (rejects if any rejects)
  • Returns array of results (same order)
  • Use case: Parallel independent requests

Promise.allSettled([promises])

  • Waits for all to settle (resolve or reject)
  • Never rejects
  • Returns array of {status, value/reason}
  • Use case: When you need all results regardless

Promise.any([promises])

  • Resolves when first promise resolves
  • Rejects only if all reject (AggregateError)
  • Use case: Racing multiple sources, first success wins

Promise.race([promises])

  • Settles with first promise that settles
  • Can resolve or reject
  • Use case: Timeout implementations

2.4 Advanced Async Patterns

Retry Logic

async function retry(fn, retries = 3, delay = 1000) {
  for (let i = 0; i < retries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === retries - 1) throw error;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

Cancellation

  • AbortController

    const controller = new AbortController();
    fetch(url, { signal: controller.signal });
    controller.abort();
  • Promise cancellation patterns

  • Race with timeout

Async Queue

  • Sequential execution of async tasks
  • Rate limiting
  • Concurrency control
  • Implementation with promises

Parallel Execution Control

  • Limit concurrent operations
  • Promise pool pattern
  • p-limit library approach

2.5 Error Handling

Try-Catch

  • Synchronous error handling
  • Works with async/await
  • Catch specific error types

Promise Error Handling

  • .catch() method
  • Error propagation
  • Global handlers

Best Practices

  • Always handle rejections
  • Specific error types
  • Logging and monitoring
  • User-friendly messages
  • Retry strategies

3. Browser Internals

3.1 Rendering Pipeline

Critical Rendering Path

  1. HTML Parsing → DOM Tree
  2. CSS Parsing → CSSOM Tree
  3. Render Tree = DOM + CSSOM
  4. Layout (Reflow) - Calculate positions
  5. Paint - Fill pixels
  6. Composite - Layer composition

DOM Construction

  • Incremental parsing
  • Tokenization
  • Tree construction
  • Script blocking

CSSOM Construction

  • CSS parsing
  • Cascade resolution
  • Specificity calculation
  • Inheritance

Render Tree

  • Only visible nodes
  • Excludes display: none
  • Combines DOM and styles
  • Pseudo-elements included

Layout (Reflow)

  • Triggers

    • Geometry changes (width, height, position)
    • Font changes
    • Content changes
    • Window resize
    • DOM manipulation
  • Performance impact

    • Expensive operation
    • Affects descendants
    • Batch DOM updates
    • Use transform over layout properties

Paint

  • Triggers

    • Color changes
    • Background changes
    • Visibility changes
    • Shadows, borders
  • Paint order

    • Background
    • Borders
    • Content
    • Outlines

Composite

  • Layers

    • Promoted elements (will-change, transform, opacity)
    • GPU acceleration
    • Layer creation cost
  • Compositing triggers

    • transform
    • opacity
    • filter
    • will-change

3.2 Performance Optimization

Reflow vs Repaint

  • Reflow: Geometry changes (expensive)
  • Repaint: Visual changes (less expensive)
  • Neither: Compositing only (cheapest)

Optimization Techniques

  • Use transform and opacity for animations
  • Batch DOM reads and writes
  • requestAnimationFrame for animations
  • Debounce scroll/resize handlers
  • Virtual scrolling for large lists
  • Code splitting
  • Lazy loading
  • Tree shaking

Critical Rendering Path Optimization

  • Minimize critical resources
  • Minimize critical bytes
  • Minimize critical path length
  • Defer non-critical CSS
  • Inline critical CSS
  • Preload key resources

Resource Hints

  • <link rel="preconnect">
  • <link rel="dns-prefetch">
  • <link rel="preload">
  • <link rel="prefetch">
  • <link rel="modulepreload">

3.3 Browser APIs

IntersectionObserver

  • Use cases

    • Lazy loading images
    • Infinite scroll
    • Ad viewability tracking
    • Animations on scroll
  • API

    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // Element is visible
        }
      });
    }, { threshold: 0.5, rootMargin: '0px' });
    
    observer.observe(element);

ResizeObserver

  • Monitor element size changes
  • Better than window resize
  • Use cases: Responsive components, charts

MutationObserver

  • Watch DOM changes
  • Configuration: attributes, childList, subtree
  • Performance considerations

PerformanceObserver

  • Monitor performance entries
  • Types: navigation, resource, measure, paint
  • Core Web Vitals monitoring

3.4 Web Workers & Service Workers

Web Workers

  • Purpose: Run JavaScript in background thread
  • Types: Dedicated, Shared
  • Communication: postMessage / onmessage
  • Limitations: No DOM access
  • Use cases: Heavy computation, data processing

Service Workers

  • Purpose: Network proxy, offline functionality

  • Lifecycle: install → activate → fetch

  • Capabilities

    • Cache API
    • Background sync
    • Push notifications
    • Offline support
  • Scope: Based on registration path

  • Update mechanism

3.5 Storage APIs

localStorage

  • Synchronous
  • 5-10MB limit
  • String-only storage
  • Same-origin policy
  • Persists across sessions

sessionStorage

  • Similar to localStorage
  • Cleared when tab closes
  • Per-tab isolation

IndexedDB

  • Asynchronous
  • Large storage (50MB+)
  • NoSQL database
  • Structured data
  • Transactions and indexes

Cache API

  • Service Worker cache
  • Request/Response pairs
  • Cache strategies

Cookies

  • 4KB limit per cookie
  • Sent with every request
  • Domain/path scoping
  • Expiration options
  • Secure/HttpOnly flags

3.6 Navigation & Loading

Navigation Timing API

  • Performance metrics
  • DNS, TCP, SSL times
  • Request/response times
  • DOM processing times

Resource Timing API

  • Individual resource metrics
  • Size, duration, caching

Page Lifecycle API

  • States: active, passive, hidden, frozen, terminated
  • Events: visibilitychange, freeze, resume
  • Battery/memory optimization

4. HTML

4.1 Semantic HTML

Structure Elements

  • <header>, <nav>, <main>, <aside>, <footer>
  • <article>, <section>
  • <figure>, <figcaption>
  • <details>, <summary>
  • <time>, <address>

Benefits

  • Accessibility
  • SEO
  • Maintainability
  • Screen reader support

Common Mistakes

  • Div soup
  • Incorrect nesting
  • Missing landmarks
  • Improper heading hierarchy

4.2 Accessibility (a11y)

ARIA Roles

  • Landmark roles: navigation, main, complementary, contentinfo
  • Widget roles: button, checkbox, tab, dialog
  • Document roles: article, document, note
  • Live regions: alert, status, log

ARIA Attributes

  • aria-label, aria-labelledby
  • aria-describedby
  • aria-hidden
  • aria-live, aria-atomic
  • aria-expanded, aria-selected
  • aria-disabled, aria-readonly

Keyboard Navigation

  • Focus management
  • Tab order
  • Skip links
  • Focus trap in modals
  • Keyboard shortcuts
  • tabindex usage

Screen Readers

  • Alt text for images
  • Form labels
  • Button text
  • Heading structure
  • Link text
  • Error messages

Focus Management

  • Visible focus indicators
  • Skip to content links
  • Focus restoration
  • Auto-focus considerations

4.3 Forms & Validation

Form Elements

  • Input types: text, email, number, tel, url, date, color, file
  • <select>, <textarea>
  • <datalist> for autocomplete
  • <fieldset> and <legend>

HTML5 Validation

  • required, pattern, min, max, minlength, maxlength
  • type attribute validation
  • Custom validity with setCustomValidity()
  • :valid, :invalid pseudo-classes

Accessibility

  • <label> association
  • Error messages with aria-describedby
  • aria-invalid attribute
  • Group related inputs

4.4 SEO & Meta Tags

Essential Meta Tags

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="...">
<meta name="keywords" content="...">
<meta name="author" content="...">
<meta name="robots" content="index, follow">

Open Graph (Social Media)

<meta property="og:title" content="...">
<meta property="og:description" content="...">
<meta property="og:image" content="...">
<meta property="og:url" content="...">
<meta property="og:type" content="website">

Twitter Cards

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="...">
<meta name="twitter:description" content="...">
<meta name="twitter:image" content="...">

Link Tags

  • Canonical: <link rel="canonical" href="...">
  • Alternate languages: <link rel="alternate" hreflang="...">
  • Icon: <link rel="icon" href="...">
  • Preconnect/prefetch (covered earlier)

4.5 HTML5 APIs

Canvas API

  • 2D drawing context
  • Animations
  • Image manipulation
  • Chart libraries

Drag and Drop API

  • draggable attribute
  • Events: dragstart, drag, dragend, dragover, drop
  • dataTransfer object

History API

  • pushState(), replaceState()
  • popstate event
  • SPA navigation

Geolocation API

  • navigator.geolocation.getCurrentPosition()
  • Watch position
  • Privacy concerns

5. CSS

5.1 Core Concepts

Box Model

  • Content, Padding, Border, Margin
  • box-sizing: border-box vs content-box
  • Collapsing margins
  • Inline vs block vs inline-block

Positioning

  • static (default)
  • relative: Relative to normal position
  • absolute: Relative to nearest positioned ancestor
  • fixed: Relative to viewport
  • sticky: Hybrid of relative and fixed

Display Types

  • block, inline, inline-block
  • flex, inline-flex
  • grid, inline-grid
  • none, contents
  • table, table-row, table-cell

Specificity

  • Inline styles (1,0,0,0)
  • IDs (0,1,0,0)
  • Classes, attributes, pseudo-classes (0,0,1,0)
  • Elements, pseudo-elements (0,0,0,1)
  • !important override (avoid)

Inheritance

  • Inherited properties: color, font-family, font-size, etc.
  • Non-inherited: margin, padding, border, display
  • inherit, initial, unset, revert keywords

Cascade

  • Origin: User agent → User → Author
  • Importance: normal → !important
  • Specificity
  • Order of appearance

5.2 Modern CSS Features

CSS Variables (Custom Properties)

:root {
  --primary-color: #3498db;
  --spacing: 1rem;
}

.button {
  background: var(--primary-color);
  padding: var(--spacing);
}

calc(), min(), max(), clamp()

width: calc(100% - 2rem);
font-size: clamp(1rem, 2vw, 2rem);
width: min(90%, 1200px);

:has() Selector (Parent Selector)

.card:has(img) {
  /* Style card if it contains an image */
}

form:has(:invalid) {
  /* Style form with invalid inputs */
}

:is(), :where(), :not()

:is(h1, h2, h3) { /* ... */ }
:where(.class1, .class2) { /* ... (0 specificity) */ }
:not(.excluded) { /* ... */ }

Container Queries

@container (min-width: 700px) {
  .card {
    display: grid;
  }
}

@layer (Cascade Layers)

@layer base, components, utilities;

@layer base {
  h1 { font-size: 2rem; }
}

Logical Properties

  • margin-inline-start instead of margin-left
  • padding-block instead of padding-top + padding-bottom
  • Better for internationalization

5.3 Layout Systems

Flexbox

  • Container properties

    • display: flex | inline-flex
    • flex-direction: row, column
    • justify-content: center, space-between, space-around, space-evenly
    • align-items: stretch, center, flex-start, flex-end
    • flex-wrap: nowrap, wrap
    • gap: spacing between items
  • Item properties

    • flex-grow, flex-shrink, flex-basis
    • flex shorthand
    • align-self
    • order
  • Use cases: Navigation, button groups, simple layouts

CSS Grid

  • Container properties

    • display: grid | inline-grid
    • grid-template-columns, grid-template-rows
    • grid-template-areas
    • gap, column-gap, row-gap
    • justify-items, align-items
    • justify-content, align-content
  • Item properties

    • grid-column, grid-row
    • grid-area
    • justify-self, align-self
  • Functions

    • repeat(), minmax(), auto-fit, auto-fill
    • fr unit
  • Use cases: Page layouts, complex grids, dashboards

Multi-column Layout

  • column-count, column-width
  • column-gap, column-rule
  • Use case: Newspaper-style layouts

5.4 Responsive Design

Mobile-First Approach

/* Base styles for mobile */
.container { padding: 1rem; }

/* Tablet and up */
@media (min-width: 768px) {
  .container { padding: 2rem; }
}

/* Desktop and up */
@media (min-width: 1024px) {
  .container { padding: 3rem; }
}

Breakpoints

  • Common: 640px (sm), 768px (md), 1024px (lg), 1280px (xl)
  • Use em/rem for accessibility

Responsive Units

  • %: Relative to parent
  • vw, vh: Viewport width/height
  • vmin, vmax: Smaller/larger of vw or vh
  • rem: Root element font size
  • em: Parent element font size
  • ch: Width of "0" character

Responsive Images

  • srcset and sizes attributes
  • <picture> element
  • Art direction with multiple sources

5.5 CSS Architecture

Naming Conventions

  • BEM (Block Element Modifier)

    .card { }
    .card__title { }
    .card--featured { }
  • OOCSS (Object-Oriented CSS)

  • SMACSS (Scalable and Modular Architecture)

  • Atomic CSS / Utility-first (Tailwind)

CSS Methodologies

  • Component-based
  • Utility-first
  • CSS Modules
  • CSS-in-JS

Organization

  • File structure
  • Import order
  • Specificity management
  • Avoiding conflicts

5.6 Performance

CSS vs JS Animations

  • CSS advantages

    • GPU acceleration
    • Off main thread
    • Better performance
  • Use CSS for: opacity, transform

  • Avoid animating: width, height, margin, padding

will-change Property

.animated {
  will-change: transform, opacity;
}
  • Creates new layer
  • Use sparingly (memory cost)
  • Remove after animation

GPU Acceleration

  • transform and opacity are GPU-accelerated
  • Use transform: translateZ(0) to force layer
  • Monitor layer creation (DevTools)

Critical CSS

  • Inline above-the-fold styles
  • Defer non-critical CSS
  • Use tools: critical, critters

5.7 Advanced Selectors & Pseudo-classes

Pseudo-classes

  • :hover, :focus, :active
  • :nth-child(), :nth-of-type()
  • :first-child, :last-child
  • :not(), :is(), :where()
  • :has() (parent selector)
  • :focus-visible, :focus-within
  • :checked, :disabled, :invalid

Pseudo-elements

  • ::before, ::after
  • ::first-line, ::first-letter
  • ::placeholder
  • ::selection
  • ::marker (list markers)

6. React

6.1 Fundamentals

JSX

  • JavaScript XML syntax
  • Expressions in curly braces
  • Self-closing tags
  • className vs class
  • Style as object
  • Comments: {/* */}

Components

  • Function components (modern approach)
  • Class components (legacy)
  • PascalCase naming
  • Props as function arguments
  • Return JSX (or null, arrays, fragments)

Props vs State

  • Props: Read-only data from parent
  • State: Component's own mutable data
  • Props flow down (unidirectional)
  • State triggers re-renders

Controlled vs Uncontrolled Components

  • Controlled: Form values controlled by React state
  • Uncontrolled: Use refs to access DOM values
  • Controlled preferred for form validation

Lifting State Up

  • Share state between components
  • Move state to closest common ancestor
  • Pass state and updaters as props

Component Composition

  • children prop
  • Render props pattern
  • Higher-Order Components (HOC)
  • Compound components

6.2 Hooks

useState

const [state, setState] = useState(initialValue);
  • State updates are batched
  • Functional updates: setState(prev => prev + 1)
  • Lazy initialization: useState(() => expensiveComputation())

useEffect

useEffect(() => {
  // Side effect
  return () => {
    // Cleanup
  };
}, [dependencies]);
  • Runs after render
  • Cleanup function
  • Dependency array
  • Common uses: data fetching, subscriptions, timers

useRef

const ref = useRef(initialValue);
  • Mutable object that persists across renders
  • .current property
  • Use cases: DOM access, storing mutable values
  • Doesn't trigger re-render on change

useMemo

const memoizedValue = useMemo(() => expensiveCalculation(), [deps]);
  • Memoize expensive computations
  • Only recalculates when dependencies change
  • Don't overuse (has overhead)

useCallback

const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);
  • Memoize function reference
  • Useful for passing callbacks to optimized children
  • Prevents unnecessary re-renders

useContext

const value = useContext(MyContext);
  • Access context without nesting
  • Alternative to prop drilling
  • Re-renders when context value changes

useReducer

const [state, dispatch] = useReducer(reducer, initialState);
  • Alternative to useState for complex state
  • Similar to Redux pattern
  • Good for state with multiple sub-values

useLayoutEffect

  • Similar to useEffect
  • Runs synchronously after DOM mutations
  • Blocks visual updates
  • Use for DOM measurements

useImperativeHandle

  • Customize ref value exposed to parent
  • Used with forwardRef
  • Rarely needed

useId

  • Generate unique IDs for accessibility
  • SSR-safe
  • Use for form labels, aria attributes

Custom Hooks

  • Extract reusable logic
  • Must start with "use"
  • Can use other hooks
  • Examples: useLocalStorage, useFetch, useDebounce

6.3 React Internals

Reconciliation

  • Process of updating DOM
  • Virtual DOM diffing
  • Key prop importance
  • Same-level comparison

Fiber Architecture

  • Reconciliation engine (React 16+)
  • Incremental rendering
  • Pause/resume/abort work
  • Priority scheduling

Virtual DOM

  • Lightweight representation of real DOM
  • Diff algorithm
  • Batching updates
  • Performance benefits

Batching

  • React 18: Automatic batching everywhere
  • React 17: Only in event handlers
  • flushSync() to opt-out

Strict Mode

  • Double-invokes effects in dev
  • Highlights potential problems
  • Deprecation warnings
  • Does not affect production

6.4 Performance Optimization

React.memo

const MemoizedComponent = React.memo(Component, arePropsEqual);
  • Prevents re-renders if props unchanged
  • Shallow comparison by default
  • Custom comparison function

useMemo & useCallback

  • Memoize values and functions
  • Reduce unnecessary calculations
  • Optimize child component re-renders

Code Splitting

  • React.lazy(() => import('./Component'))
  • Dynamic imports
  • Route-based splitting
  • Component-based splitting

Suspense

<Suspense fallback={<Loading />}>
  <LazyComponent />
</Suspense>
  • Handle loading states
  • Works with React.lazy
  • Future: data fetching

Keys in Lists

  • Stable identity for elements
  • Avoid using index as key
  • Use unique IDs
  • Improves reconciliation performance

Avoid Re-renders

  • Move state down
  • Split large components
  • Use composition (children prop)
  • Memoization
  • Proper key usage

Profiler API

  • Measure component render performance
  • <Profiler id="..." onRender={callback}>
  • Chrome DevTools Profiler

6.5 Advanced Patterns

Render Props

<DataProvider render={data => <Display data={data} />} />

Higher-Order Components (HOC)

const EnhancedComponent = withFeature(Component);

Compound Components

  • Multiple components work together
  • Share implicit state
  • Example: Tabs component

Controlled Props

  • Allow parent to control component state
  • Both controlled and uncontrolled modes

State Reducers

  • Give users control over state updates
  • Pass custom reducer

Portals

ReactDOM.createPortal(child, container);
  • Render outside parent DOM hierarchy
  • Use cases: Modals, tooltips

6.6 Error Handling

Error Boundaries

class ErrorBoundary extends React.Component {
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  
  componentDidCatch(error, errorInfo) {
    logErrorToService(error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return <FallbackUI />;
    }
    return this.props.children;
  }
}
  • Catch errors in child components
  • Only class components can be error boundaries
  • Don't catch: event handlers, async code, SSR, errors in boundary itself

Error Boundary Best Practices

  • Place at route level
  • Granular boundaries for critical sections
  • Logging integration
  • Reset functionality

6.7 Concurrent Features

Transitions

import { startTransition } from 'react';

startTransition(() => {
  setState(newState); // Mark as non-urgent
});

useTransition Hook

const [isPending, startTransition] = useTransition();

useDeferredValue

const deferredValue = useDeferredValue(value);
  • Defer updating non-urgent parts
  • Useful for debouncing expensive renders

Concurrent Rendering

  • Non-blocking rendering
  • Prioritize urgent updates
  • Improves perceived performance

6.8 Server Components (RSC)

Server vs Client Components

  • Server Components: Run on server, no client JS
  • Client Components: Traditional React components
  • 'use client' directive

Benefits

  • Reduced bundle size
  • Direct database/API access
  • Better security (secrets stay on server)
  • Automatic code splitting

Streaming SSR

  • Send HTML in chunks
  • Progressive hydration
  • Faster time-to-interactive

7. Next.js & Meta-Frameworks

7.1 App Router vs Pages Router

Pages Router (Legacy)

  • pages/ directory
  • File-based routing
  • getServerSideProps, getStaticProps
  • Client-side routing with next/link

App Router (Next.js 13+)

  • app/ directory
  • Nested layouts
  • Server Components by default
  • Streaming and Suspense
  • Better developer experience

7.2 Rendering Strategies

SSR (Server-Side Rendering)

  • HTML generated per request
  • Fresh data
  • Slower TTFB
  • Good for: Dynamic content, personalization

SSG (Static Site Generation)

  • HTML generated at build time
  • Fast delivery via CDN
  • Stale data until rebuild
  • Good for: Marketing pages, blogs

ISR (Incremental Static Regeneration)

  • Static with periodic updates
  • Revalidate at intervals or on-demand
  • Best of SSG and SSR

CSR (Client-Side Rendering)

  • Traditional SPA behavior
  • Data fetching on client
  • Good for: Dashboards, authenticated pages

7.3 Data Fetching

App Router

  • Server Components: async/await directly
  • Client Components: use client-side fetching
  • fetch with caching options

Pages Router

  • getServerSideProps: SSR
  • getStaticProps: SSG
  • getStaticPaths: Dynamic routes
  • getInitialProps: Legacy

Caching

  • fetch with cache option
  • Revalidation strategies
  • Route segment config

7.4 Routing & Navigation

File-based Routing

  • Folder = route segment
  • page.tsx = route UI
  • layout.tsx = shared UI
  • loading.tsx = loading UI
  • error.tsx = error UI

Dynamic Routes

  • [id] = single segment
  • [...slug] = catch-all
  • [[...slug]] = optional catch-all

Route Groups

  • (folder) = group without affecting URL
  • Organize routes logically

Parallel Routes

  • @folder = parallel route
  • Load multiple pages in same layout

Intercepting Routes

  • (.) = intercept same level
  • Useful for modals

7.5 Optimization Features

Image Optimization

import Image from 'next/image'

<Image src="..." alt="..." width={500} height={300} />
  • Automatic optimization
  • Lazy loading
  • Modern formats (WebP, AVIF)
  • Responsive images

Font Optimization

import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })
  • Automatic font optimization
  • No layout shift
  • Self-hosting

Script Optimization

import Script from 'next/script'

<Script src="..." strategy="lazyOnload" />
  • Deferred loading
  • Strategy options

Metadata API

  • SEO optimization
  • Dynamic metadata
  • OpenGraph, Twitter cards

7.6 Middleware & Edge

Middleware

export function middleware(request) {
  // Run before request is completed
}

export const config = {
  matcher: '/about/:path*',
}
  • Authentication
  • Redirects
  • Header manipulation
  • A/B testing

Edge Runtime

  • Lightweight runtime
  • Fast cold starts
  • Deploy globally
  • Limited Node.js APIs

7.7 Other Frameworks

Remix

  • Nested routing
  • Progressive enhancement
  • Form handling
  • Error boundaries

Gatsby

  • GraphQL data layer
  • Plugin ecosystem
  • Image optimization
  • SSG focus

Astro

  • Multi-framework support
  • Partial hydration
  • Islands architecture
  • Content-focused

8. State Management

8.1 Local vs Global State

Local State

  • Component-specific
  • useState, useReducer
  • Doesn't need sharing
  • Examples: Form inputs, toggle states

Global State

  • Shared across components
  • Needs state management solution
  • Examples: User auth, theme, cart

Lifting State Up

  • Move state to common ancestor
  • Pass as props
  • Simple solution for related components

8.2 Context API

Creating Context

const ThemeContext = createContext(defaultValue);

Provider

<ThemeContext.Provider value={theme}>
  {children}
</ThemeContext.Provider>

Consumer

const theme = useContext(ThemeContext);

Context Pitfalls

  • Performance: All consumers re-render on value change
  • Solution: Split contexts, memoize values
  • Anti-pattern: Using for all state

Optimization

const value = useMemo(() => ({ 
  state, 
  dispatch 
}), [state]);

8.3 Redux Toolkit

Store Setup

import { configureStore } from '@reduxjs/toolkit'

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
})

Creating Slices

import { createSlice } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: state => { state.value += 1 },
    decrement: state => { state.value -= 1 },
  },
})

Async Thunks

import { createAsyncThunk } from '@reduxjs/toolkit'

const fetchUser = createAsyncThunk(
  'users/fetch',
  async (userId) => {
    const response = await fetch(`/api/user/${userId}`)
    return response.json()
  }
)

Hooks

  • useSelector(selector)
  • useDispatch()
  • Memoized selectors with Reselect

8.4 Modern Solutions

Zustand

import create from 'zustand'

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}))
  • Simple API
  • No boilerplate
  • Minimal re-renders

Jotai

import { atom, useAtom } from 'jotai'

const countAtom = atom(0)

function Counter() {
  const [count, setCount] = useAtom(countAtom)
}
  • Atomic state
  • Bottom-up approach
  • TypeScript-first

Recoil

  • Atom-based
  • Derived state (selectors)
  • Async queries

Valtio

  • Proxy-based
  • Mutable API
  • Auto-tracking

8.5 Server State

React Query / TanStack Query

import { useQuery } from '@tanstack/react-query'

function Users() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['users'],
    queryFn: fetchUsers,
  })
}

Features

  • Caching
  • Background refetching
  • Stale data handling
  • Pagination
  • Infinite queries
  • Mutations
  • Optimistic updates

SWR (Stale-While-Revalidate)

import useSWR from 'swr'

function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)
}

8.6 URL State

Query Parameters

  • useSearchParams (Next.js)
  • URLSearchParams API
  • Sync state with URL

Benefits

  • Shareable links
  • Browser history
  • Bookmark-friendly

8.7 Form State

React Hook Form

import { useForm } from 'react-hook-form'

function Form() {
  const { register, handleSubmit, formState: { errors } } = useForm()
}

Formik

  • Form state management
  • Validation
  • Error handling

9. Testing

9.1 Testing Types

Unit Testing

  • Test individual functions/components
  • Fast execution
  • High coverage
  • Mock dependencies

Integration Testing

  • Test component interactions
  • Multiple units together
  • More realistic scenarios

E2E (End-to-End) Testing

  • Test entire application flow
  • User perspective
  • Slower, more brittle
  • Critical paths only

Visual Regression Testing

  • Detect UI changes
  • Screenshot comparison
  • Prevent visual bugs

9.2 Unit Testing

Jest / Vitest

describe('sum', () => {
  test('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3);
  });
});

Features

  • Test runner
  • Assertion library
  • Mocking utilities
  • Code coverage

Mocking

jest.mock('./api')
jest.fn()
jest.spyOn(object, 'method')

9.3 Component Testing

React Testing Library

import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

test('button click', async () => {
  render(<Button />)
  const button = screen.getByRole('button')
  await userEvent.click(button)
  expect(screen.getByText('Clicked')).toBeInTheDocument()
})

Principles

  • Test behavior, not implementation
  • Query by accessibility
  • Avoid testing state directly
  • User-centric testing

Queries

  • getByRole (preferred)
  • getByLabelText
  • getByText
  • getByTestId (last resort)
  • findBy for async
  • queryBy for non-existence

User Interactions

  • userEvent.click()
  • userEvent.type()
  • userEvent.keyboard()
  • Better than fireEvent

9.4 E2E Testing

Playwright

import { test, expect } from '@playwright/test'

test('login flow', async ({ page }) => {
  await page.goto('https://example.com')
  await page.fill('input[name="email"]', 'user@example.com')
  await page.click('button[type="submit"]')
  await expect(page).toHaveURL(/dashboard/)
})

Cypress

describe('Login', () => {
  it('should login successfully', () => {
    cy.visit('/login')
    cy.get('input[name="email"]').type('user@example.com')
    cy.get('button').click()
    cy.url().should('include', '/dashboard')
  })
})

Best Practices

  • Independent tests
  • Data seeding
  • Cleanup between tests
  • Parallel execution
  • Record videos on failure

9.5 Testing Strategies

Test Pyramid

  • Many unit tests (fast, cheap)
  • Some integration tests
  • Few E2E tests (slow, expensive)

Mocking APIs

  • MSW (Mock Service Worker)
  • Intercept network requests
  • Realistic responses

Snapshot Testing

  • Capture component output
  • Detect unintended changes
  • Pros: Quick to write
  • Cons: Can be brittle, large diffs

9.6 Visual Regression Testing

Tools

  • Percy
  • Chromatic
  • Applitools

Process

  • Capture baseline screenshots
  • Compare on changes
  • Review and approve differences

9.7 Performance Testing

Lighthouse CI

  • Automated performance testing
  • CI/CD integration
  • Budget enforcement

Metrics to Track

  • LCP, FID, CLS
  • Bundle size
  • Time to Interactive

10. Frontend System Design

10.1 Common Questions

Design a Product Listing Page

  • Pagination vs infinite scroll
  • Filtering and sorting
  • Search functionality
  • State management
  • Caching strategy
  • Performance optimization

Design Infinite Scroll

  • IntersectionObserver
  • Pagination API
  • Loading states
  • Error handling
  • Memory management
  • Skeleton screens

Design Search with Debounce

  • Input handling
  • Debounce implementation
  • API requests
  • Loading/error states
  • Result caching
  • Autocomplete

Design Offline-first App

  • Service Worker
  • Cache strategies
  • Background sync
  • IndexedDB
  • Conflict resolution
  • Online/offline detection

Design Auth Flow

  • JWT storage
  • Refresh tokens
  • Token expiration
  • Secure storage
  • CSRF protection
  • Session management

Design Micro-frontend Architecture

  • Module Federation
  • Shared dependencies
  • Communication between apps
  • Deployment strategy
  • Versioning

10.2 Architecture Patterns

Component Architecture

  • Atomic design
  • Container/Presentational
  • Composition patterns
  • Props drilling solutions

Folder Structure

  • Feature-based
  • Layer-based
  • Atomic structure
  • Colocation

API Layer

  • Centralized API client
  • Error handling
  • Interceptors
  • Request/response transformation

10.3 Caching Strategies

Browser Caching

  • HTTP Cache-Control headers
  • ETag/If-None-Match
  • Service Worker caching

Application Caching

  • In-memory cache
  • React Query / SWR
  • Cache invalidation strategies
  • Stale-while-revalidate

CDN Caching

  • Static asset caching
  • Edge caching
  • Cache purging

10.4 Data Management

Pagination

  • Offset-based
  • Cursor-based
  • Pros/cons of each
  • UI considerations

Infinite Scroll

  • Virtual scrolling
  • Windowing (react-window, react-virtualized)
  • Load more trigger
  • Performance optimization

Real-time Updates

  • WebSockets
  • Server-Sent Events (SSE)
  • Polling
  • Long polling

Optimistic Updates

  • Immediate UI feedback
  • Rollback on failure
  • Conflict resolution

10.5 Real-time Features

WebSockets

  • Bidirectional communication
  • Connection management
  • Reconnection logic
  • Message queuing

Server-Sent Events

  • Unidirectional (server to client)
  • Auto-reconnection
  • Event types
  • Use cases

Polling

  • Short polling vs long polling
  • Trade-offs
  • When to use

10.6 Scalability

Code Splitting

  • Route-based
  • Component-based
  • Lazy loading
  • Dynamic imports

Bundle Optimization

  • Tree shaking
  • Code splitting
  • Compression
  • Minification

State Management at Scale

  • Normalized state
  • Selector memoization
  • State slicing
  • Middleware

10.7 Monitoring & Observability

Error Tracking

  • Sentry
  • LogRocket
  • Error boundaries
  • Source maps

Analytics

  • User behavior tracking
  • Conversion funnels
  • A/B testing
  • Feature flags

Performance Monitoring

  • Real User Monitoring (RUM)
  • Synthetic monitoring
  • Core Web Vitals tracking

11. Security

11.1 Common Vulnerabilities

XSS (Cross-Site Scripting)

  • Types: Stored, Reflected, DOM-based
  • Prevention
    • Sanitize user input
    • Use textContent instead of innerHTML
    • Content Security Policy
    • React auto-escapes by default
    • DOMPurify for HTML sanitization

CSRF (Cross-Site Request Forgery)

  • Attack: Unauthorized actions on behalf of user
  • Prevention
    • CSRF tokens
    • SameSite cookie attribute
    • Custom headers
    • Double submit cookies

Clickjacking

  • Attack: Invisible iframe overlay
  • Prevention
    • X-Frame-Options header
    • CSP frame-ancestors directive
    • Frame-busting scripts

Open Redirect

  • Attack: Redirect to malicious site
  • Prevention
    • Validate redirect URLs
    • Whitelist allowed domains
    • Avoid user-controlled redirects

11.2 Authentication & Authorization

JWT (JSON Web Tokens)

  • Structure: Header.Payload.Signature
  • Storage: Where to store?
    • localStorage: Vulnerable to XSS
    • sessionStorage: Same as localStorage
    • Cookies (HttpOnly, Secure, SameSite): Preferred
    • Memory: Lost on refresh

Refresh Tokens

  • Long-lived token
  • Rotate access tokens
  • Store securely
  • Revocation mechanism

OAuth 2.0

  • Authorization framework
  • Flows: Authorization Code, Implicit, Client Credentials
  • Third-party login

Best Practices

  • Use HTTPS
  • Secure cookie flags
  • Token expiration
  • Logout functionality
  • Session management

11.3 Secure Data Handling

Sensitive Data

  • Never expose secrets in frontend
  • Encrypt in transit (HTTPS)
  • Mask sensitive input (passwords)
  • Secure form submissions

API Keys

  • Never commit to version control
  • Environment variables
  • Backend proxy for API calls

PII (Personally Identifiable Information)

  • Minimize collection
  • Secure storage
  • Consent management
  • GDPR compliance

11.4 Content Security

Content Security Policy (CSP)

<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; script-src 'self' https://trusted.cdn.com">
  • Whitelist sources
  • Prevent XSS
  • Report violations

CORS (Cross-Origin Resource Sharing)

  • Restrict cross-origin requests
  • Preflight requests
  • Allowed origins configuration

Subresource Integrity (SRI)

<script src="https://cdn.com/library.js"
        integrity="sha384-..."
        crossorigin="anonymous"></script>

11.5 API Security

Input Validation

  • Client-side (UX)
  • Server-side (security)
  • Sanitize inputs
  • Type checking

Rate Limiting

  • Prevent abuse
  • DDoS protection
  • Per-user limits

HTTPS

  • Encrypt data in transit
  • SSL/TLS certificates
  • HSTS header

12. Performance & Optimization

12.1 Core Web Vitals

LCP (Largest Contentful Paint)

  • Target: < 2.5s
  • Measures: Render time of largest element
  • Optimization
    • Optimize images
    • Preload resources
    • Reduce server response time
    • Minimize render-blocking resources

FID (First Input Delay) / INP (Interaction to Next Paint)

  • Target: < 100ms (FID), < 200ms (INP)
  • Measures: Input responsiveness
  • Optimization
    • Reduce JavaScript execution
    • Code splitting
    • Web Workers for heavy tasks
    • Debounce/throttle

CLS (Cumulative Layout Shift)

  • Target: < 0.1
  • Measures: Visual stability
  • Optimization
    • Size attributes on images/videos
    • Reserve space for ads
    • Avoid inserting content above fold
    • Web fonts with font-display

12.2 Loading Performance

Critical Rendering Path

  • Minimize critical resources
  • Reduce critical bytes
  • Optimize critical path length

Resource Loading

  • Preload: <link rel="preload">
  • Prefetch: <link rel="prefetch">
  • DNS-prefetch: <link rel="dns-prefetch">
  • Preconnect: <link rel="preconnect">

Code Splitting

  • Route-based splitting
  • Component-based splitting
  • Dynamic imports
  • Webpack chunks

Lazy Loading

  • Images: loading="lazy"
  • Components: React.lazy
  • Intersection Observer
  • Below-the-fold content

Tree Shaking

  • Remove unused code
  • ES6 modules
  • Side-effect free code
  • Webpack/Rollup optimization

12.3 Runtime Performance

JavaScript Performance

  • Avoid long tasks (>50ms)
  • Use Web Workers
  • Debounce/throttle
  • RequestAnimationFrame

React Performance

  • React.memo
  • useMemo / useCallback
  • Virtual scrolling
  • Lazy loading
  • Code splitting

Rendering Performance

  • Use CSS transforms
  • Avoid layout thrashing
  • Batch DOM updates
  • will-change property

12.4 Network Optimization

Reducing Requests

  • Bundle files
  • Sprite images
  • Inline critical CSS
  • HTTP/2 multiplexing

Compression

  • Gzip / Brotli
  • Text compression
  • Image compression

Caching

  • Browser caching
  • Service Worker caching
  • CDN caching

12.5 Measurement & Monitoring

Tools

  • Lighthouse
  • WebPageTest
  • Chrome DevTools Performance
  • Real User Monitoring (RUM)

Metrics

  • TTFB (Time to First Byte)
  • FCP (First Contentful Paint)
  • LCP, FID/INP, CLS
  • Time to Interactive (TTI)

Performance Budgets

  • Set limits for metrics
  • Fail builds on violations
  • Bundle size budgets

12.6 Image Optimization

Formats

  • WebP, AVIF (modern)
  • JPEG (photos)
  • PNG (transparency)
  • SVG (icons, logos)

Techniques

  • Responsive images (srcset)
  • Lazy loading
  • Image CDN
  • Compression
  • Blur placeholder

Next.js Image

  • Automatic optimization
  • Modern formats
  • Lazy loading
  • Size optimization

12.7 Font Optimization

Loading Strategies

  • font-display: swap, block, fallback, optional
  • Preload fonts
  • Self-host fonts
  • Variable fonts

FOUT/FOIT

  • Flash of Unstyled Text
  • Flash of Invisible Text
  • font-display: swap to prevent FOIT

13. Build Tools & Ecosystem

13.1 Bundlers

Webpack

  • Mature, widely used
  • Plugin ecosystem
  • Complex configuration
  • Module federation

Vite

  • Fast dev server (esbuild)
  • HMR (Hot Module Replacement)
  • Rollup for production
  • Modern tooling

Rollup

  • ES modules focus
  • Tree shaking
  • Library bundling
  • Simple configuration

esbuild

  • Extremely fast
  • Written in Go
  • Limited plugin ecosystem
  • Good for libraries

Parcel

  • Zero config
  • Fast build times
  • Built-in optimizations

13.2 Transpilers

Babel

  • Transform modern JS
  • Plugin system
  • Preset configurations
  • JSX support

TypeScript Compiler (tsc)

  • Type checking
  • JS generation
  • Declaration files

SWC (Speedy Web Compiler)

  • Rust-based
  • Much faster than Babel
  • Drop-in replacement

13.3 Package Managers

npm

  • Default Node.js package manager
  • Largest registry
  • package-lock.json

yarn

  • Fast, reliable
  • Workspaces support
  • Plug'n'Play (PnP)

pnpm

  • Efficient disk usage
  • Strict node_modules
  • Fast installation
  • Monorepo support

13.4 Monorepos

Nx

  • Build system
  • Code generation
  • Dependency graph
  • Cache optimization

Turborepo

  • High-performance builds
  • Remote caching
  • Incremental builds
  • Simple setup

Lerna

  • Multi-package management
  • Versioning
  • Publishing
  • Bootstrap packages

Workspaces

  • npm/yarn/pnpm workspaces
  • Share dependencies
  • Link packages

13.5 Module Federation

Webpack Module Federation

  • Share code between apps
  • Runtime integration
  • Independent deployment
  • Micro-frontends

Use Cases

  • Micro-frontends
  • Shared components
  • Plugin architectures

13.6 CI/CD

GitHub Actions

  • Automated workflows
  • Build, test, deploy
  • Matrix builds

GitLab CI

  • .gitlab-ci.yml
  • Pipelines
  • Runners

Jenkins

  • Automation server
  • Plugin ecosystem
  • Self-hosted

Best Practices

  • Automated testing
  • Linting
  • Build verification
  • Deployment pipelines
  • Environment management

14. TypeScript

14.1 Type System Fundamentals

Basic Types

let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
let items: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];

Type Inference

  • TypeScript infers types when possible
  • Explicit types when needed
  • Contextual typing

Type Annotations

  • Variable types
  • Function parameters
  • Return types

Union Types

let value: string | number;

Intersection Types

type A = { name: string };
type B = { age: number };
type C = A & B; // { name: string, age: number }

Literal Types

let status: "success" | "error" | "pending";

14.2 Advanced Types

Conditional Types

type IsString<T> = T extends string ? true : false;

Mapped Types

type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

Template Literal Types

type EventName<T extends string> = `${T}Changed`;

Index Types

type Person = { name: string; age: number };
type PersonKeys = keyof Person; // "name" | "age"

14.3 Utility Types

Partial

  • Makes all properties optional

Required

  • Makes all properties required

Readonly

  • Makes all properties readonly

Pick<T, K>

  • Pick specific properties

Omit<T, K>

  • Omit specific properties

Record<K, T>

  • Object type with specific keys and values

Exclude<T, U>

  • Exclude types from union

Extract<T, U>

  • Extract types from union

NonNullable

  • Remove null and undefined

ReturnType

  • Get function return type

Parameters

  • Get function parameter types

14.4 Generics

Generic Functions

function identity<T>(arg: T): T {
  return arg;
}

Generic Interfaces

interface Box<T> {
  value: T;
}

Generic Constraints

function getProperty<T, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}

Default Generic Types

interface Container<T = string> {
  value: T;
}

14.5 Type Guards & Narrowing

typeof Guards

if (typeof x === "string") {
  // x is string here
}

instanceof Guards

if (x instanceof Date) {
  // x is Date here
}

Custom Type Guards

function isString(value: any): value is string {
  return typeof value === "string";
}

Discriminated Unions

type Shape = 
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number };

function area(shape: Shape) {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.size ** 2;
  }
}

14.6 Configuration

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

Strict Mode Options

  • strictNullChecks
  • strictFunctionTypes
  • strictBindCallApply
  • strictPropertyInitialization
  • noImplicitThis
  • noImplicitAny

14.7 React with TypeScript

Component Props

interface Props {
  name: string;
  age?: number;
  onClick: () => void;
}

const Component: React.FC<Props> = ({ name, age, onClick }) => {
  return <div onClick={onClick}>{name}</div>;
};

Hooks

const [state, setState] = useState<string>("");
const ref = useRef<HTMLDivElement>(null);

Event Handlers

const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
  // ...
};

15. DSA for Frontend

15.1 Data Structures

Arrays

  • Push, pop, shift, unshift
  • Map, filter, reduce
  • Slice, splice
  • Sort algorithms

Linked Lists

  • Singly linked list
  • Doubly linked list
  • Use cases: LRU cache

Stacks

  • LIFO principle
  • Operations: push, pop, peek
  • Use cases: Undo/redo, expression evaluation

Queues

  • FIFO principle
  • Operations: enqueue, dequeue
  • Use cases: Task scheduling, BFS

Hash Tables (Objects/Maps)

  • O(1) lookup
  • Collision handling
  • Use cases: Caching, counting

Trees

  • Binary trees
  • Binary search trees
  • Use cases: DOM structure, file systems

Graphs

  • Nodes and edges
  • Use cases: Network topology, dependencies

15.2 Common Patterns

Two Pointers

  • Start and end pointers
  • Use cases: Palindrome, two sum in sorted array

Sliding Window

  • Fixed or dynamic window
  • Use cases: Subarray problems, longest substring

Hash Map

  • Frequency counting
  • Use cases: Two sum, anagrams

Recursion

  • Base case + recursive case
  • Use cases: Tree traversal, backtracking

Dynamic Programming

  • Memoization (top-down)
  • Tabulation (bottom-up)
  • Use cases: Fibonacci, coin change

15.3 Frontend-Specific Problems

Deep Clone

  • Recursive clone
  • Handle circular references
  • structuredClone() API

Flatten Object

function flatten(obj, prefix = '') {
  let result = {};
  for (let key in obj) {
    const newKey = prefix ? `${prefix}.${key}` : key;
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      Object.assign(result, flatten(obj[key], newKey));
    } else {
      result[newKey] = obj[key];
    }
  }
  return result;
}

Debounce

function debounce(fn, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  };
}

Throttle

function throttle(fn, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      fn.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

Event Emitter

class EventEmitter {
  constructor() {
    this.events = {};
  }
  
  on(event, listener) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(listener);
  }
  
  emit(event, ...args) {
    if (this.events[event]) {
      this.events[event].forEach(listener => listener(...args));
    }
  }
  
  off(event, listenerToRemove) {
    if (this.events[event]) {
      this.events[event] = this.events[event].filter(
        listener => listener !== listenerToRemove
      );
    }
  }
}

Virtual DOM Diff

  • Simplified reconciliation
  • Tree comparison
  • Minimal updates

LRU Cache

class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.cache = new Map();
  }
  
  get(key) {
    if (!this.cache.has(key)) return -1;
    const value = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, value);
    return value;
  }
  
  put(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    }
    this.cache.set(key, value);
    if (this.cache.size > this.capacity) {
      this.cache.delete(this.cache.keys().next().value);
    }
  }
}

15.4 Algorithm Complexity

Time Complexity

  • O(1): Constant
  • O(log n): Logarithmic
  • O(n): Linear
  • O(n log n): Linearithmic
  • O(n²): Quadratic
  • O(2ⁿ): Exponential

Space Complexity

  • Auxiliary space
  • In-place algorithms
  • Trade-offs

16. Web APIs & Browser Features

16.1 Storage

localStorage / sessionStorage

localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
localStorage.removeItem('key');
localStorage.clear();

IndexedDB

  • Asynchronous
  • Transactional database
  • Large storage capacity

Cache API

  • Service Worker cache
  • Cache first/network first strategies

16.2 Geolocation & Sensors

Geolocation API

navigator.geolocation.getCurrentPosition(
  position => console.log(position.coords),
  error => console.error(error)
);

Device Orientation

  • Accelerometer
  • Gyroscope
  • Magnetometer

16.3 Media APIs

getUserMedia (WebRTC)

navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  .then(stream => {
    videoElement.srcObject = stream;
  });

Web Audio API

  • Audio processing
  • Synthesizers
  • Visualizations

Media Session API

  • Control media playback
  • Lock screen controls

16.4 Communication APIs

Fetch API

fetch('/api/data')
  .then(response => response.json())
  .then(data => console.log(data));

WebSockets

const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = (event) => console.log(event.data);
ws.send('message');

Server-Sent Events

const eventSource = new EventSource('/events');
eventSource.onmessage = (event) => {
  console.log(event.data);
};

Broadcast Channel API

  • Communication between tabs
const channel = new BroadcastChannel('my-channel');
channel.postMessage('Hello');
channel.onmessage = (event) => console.log(event.data);

16.5 Background APIs

Background Sync

  • Sync when online
  • Service Worker feature

Background Fetch

  • Large downloads
  • Continues after page close

Periodic Background Sync

  • Scheduled syncs
  • Permission required

17. GraphQL

17.1 Core Concepts

Queries

query GetUser($id: ID!) {
  user(id: $id) {
    id
    name
    email
  }
}

Mutations

mutation CreateUser($input: UserInput!) {
  createUser(input: $input) {
    id
    name
  }
}

Subscriptions

subscription OnMessageAdded {
  messageAdded {
    id
    content
    author
  }
}

Fragments

fragment UserFields on User {
  id
  name
  email
}

17.2 Client Libraries

Apollo Client

  • Caching
  • Optimistic UI
  • Local state management
  • DevTools

urql

  • Lightweight
  • Extensible
  • Normalized cache (optional)

Relay

  • Fragment colocation
  • Pagination
  • Optimized for large apps

17.3 Advanced Patterns

Optimistic Updates

  • Immediate UI feedback
  • Rollback on error

Pagination

  • Cursor-based
  • Offset-based
  • Relay connections

Caching

  • Normalized cache
  • Cache policies
  • Cache updates

18. Progressive Web Apps (PWA)

18.1 PWA Fundamentals

Manifest File

{
  "name": "My App",
  "short_name": "App",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#000000",
  "icons": [...]
}

Service Worker

  • Lifecycle: install → activate → fetch
  • Cache strategies
  • Offline functionality

Install Prompt

  • beforeinstallprompt event
  • Custom install UI
  • Add to home screen

18.2 Offline Strategies

Cache First

  • Serve from cache, fallback to network

Network First

  • Try network, fallback to cache

Stale While Revalidate

  • Serve cache, update in background

Network Only / Cache Only

  • Specific use cases

18.3 App-like Features

Push Notifications

  • Service Worker notifications
  • Permission handling
  • Notification API

Background Sync

  • Sync when online
  • Queue requests

App Shortcuts

  • Manifest shortcuts
  • Quick actions

19. Web Performance Budget

Metrics to Budget

  • Bundle size (JS, CSS)
  • Image size
  • Number of requests
  • LCP, FID, CLS
  • Time to Interactive

Enforcement

  • Webpack bundle analyzer
  • Lighthouse CI
  • Build fails on violations

20. Micro-frontends

Approaches

  • Server-side composition
  • Build-time composition
  • Run-time composition
  • iframe-based

Module Federation

  • Webpack feature
  • Share code at runtime
  • Independent deployment

Communication

  • Custom events
  • Shared state
  • Props (for nested MFEs)

21. Internationalization (i18n)

Libraries

  • react-i18next
  • formatjs
  • LinguiJS

Considerations

  • Text direction (LTR/RTL)
  • Date/time formatting
  • Number/currency formatting
  • Pluralization
  • Translation management

22. Animation & Motion

CSS Animations

  • Transitions
  • Keyframe animations
  • Transform and opacity for performance

JavaScript Libraries

  • Framer Motion
  • GSAP
  • React Spring

Principles

  • Performance (60fps)
  • Reduced motion preference
  • Meaningful motion

23. Web Components

Custom Elements

class MyElement extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<p>Hello</p>`;
  }
}
customElements.define('my-element', MyElement);

Shadow DOM

  • Encapsulation
  • Scoped styles

HTML Templates

  • <template> element
  • Clone and use

24. Debugging & Dev Tools

Chrome DevTools

  • Elements, Console, Network
  • Performance profiler
  • Memory profiler
  • Lighthouse

React DevTools

  • Component tree
  • Props and state inspection
  • Profiler

Debugging Techniques

  • Breakpoints
  • Console methods
  • Source maps
  • Network throttling

25. Design Systems

Components

  • Atomic design principles
  • Reusable component library
  • Documentation (Storybook)

Tokens

  • Design tokens (colors, spacing, typography)
  • Theme configuration

Tools

  • Storybook
  • Figma integration
  • Component generators

26. Behavioral & System Design Interview Tips

Behavioral Questions

  • STAR method (Situation, Task, Action, Result)
  • Prepare examples of: conflict, failure, leadership, technical decisions
  • Show learning and growth

System Design Approach

  1. Clarify requirements: Functional and non-functional
  2. High-level design: Components and data flow
  3. Deep dive: Specific areas based on interviewer focus
  4. Trade-offs: Discuss pros/cons of decisions
  5. Scalability: How to handle growth

Communication

  • Think out loud
  • Ask clarifying questions
  • Draw diagrams
  • Discuss trade-offs
  • Be honest about unknowns

Key Takeaways for 2026 Interviews

  1. Browser Internals are critical — understand rendering pipeline deeply
  2. React Server Components and Next.js App Router are mainstream
  3. TypeScript is expected, not optional
  4. Performance (Core Web Vitals) is a major focus
  5. System Design questions are common for mid+ levels
  6. Testing is non-negotiable — know Jest, RTL, Playwright
  7. Modern CSS (Container Queries, :has(), etc.) is important
  8. Security awareness is expected
  9. Real project experience matters more than memorization
  10. Communication skills are as important as technical knowledge

Good luck with your interviews! 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment