Skip to main content

Web/Frontend Concept Questions

This section covers foundational concepts tested in frontend interviews. Questions assess understanding of browser internals, JavaScript behavior, and framework implementation details.

JavaScript Fundamentals

Q1: Explain the event loop

JavaScript executes on a single thread. The event loop enables asynchronous operations without blocking execution.

Components:

ComponentFunction
Call StackExecutes synchronous code
Web APIsHandle async operations (setTimeout, fetch)
Callback QueueHolds callbacks ready for execution
Microtask QueueHolds Promise callbacks (higher priority than callback queue)

Execution order:

  1. Execute all synchronous code on the call stack
  2. Process all microtasks (Promises)
  3. Process one macrotask (setTimeout callback)
  4. Repeat

Q2: Differences between var, let, and const

Featurevarletconst
ScopeFunctionBlockBlock
HoistingYes (initialized to undefined)Yes (TDZ)Yes (TDZ)
ReassignmentYesYesNo
RedeclarationYesNoNo

TDZ (Temporal Dead Zone): The period between entering a scope and the variable declaration where accessing the variable throws a ReferenceError.

Usage guidelines:

  • Use const by default
  • Use let when reassignment is required
  • Avoid var in modern JavaScript

Q3: Closures

A closure is a function that retains access to variables from its lexical scope, even after the outer function has returned.

Example: A createCounter function returns an inner function. The inner function has access to the count variable from the outer function's scope, even after createCounter has returned. Each call to the returned function increments and returns the count (1, then 2, and so on).

Use cases:

Use CaseDescription
Data encapsulationPrivate variables inaccessible from outer scope
Function factoriesFunctions that generate configured functions
State in callbacksMaintaining state across asynchronous operations

Q4: Difference between == and ===

OperatorBehavior
== (loose equality)Compares values after type coercion
=== (strict equality)Compares values and types without coercion

Examples: With loose equality, 1 == '1' returns true because the string is coerced to a number. With strict equality, 1 === '1' returns false because the types differ. Similarly, null == undefined is true with loose equality but false with strict equality.

Use === to avoid unexpected type coercion behavior.

Q5: The this keyword

The value of this is determined by how a function is called, not where it is defined.

Call Contextthis Value
Global scopewindow (or undefined in strict mode)
Object methodThe object
Constructor (new)The new instance
call/apply/bindExplicitly specified value
Arrow functionInherited from enclosing lexical scope

Arrow functions do not have their own this binding. They use this from the surrounding scope.

DOM and Browser

Q6: Event bubbling and capturing

Event propagation occurs in three phases:

PhaseDescription
Capture phaseEvent travels from document root to target element
Target phaseEvent reaches the target element
Bubble phaseEvent travels from target back up to document root

Listener registration: By default, addEventListener registers handlers for the bubble phase. To register for the capture phase instead, pass true as the third argument.

Event delegation: Attach a single event listener to a parent element instead of multiple listeners on child elements. Events bubble up from children to the parent handler.

Q7: Critical rendering path

The browser renders a page through these steps:

StepOutput
Parse HTMLDOM Tree
Parse CSSCSSOM Tree
CombineRender Tree
LayoutElement positions and sizes
PaintPixels on screen
CompositeLayer composition

Optimization techniques:

  • Minimize render-blocking resources (CSS, synchronous JS)
  • Inline critical CSS
  • Defer non-critical JavaScript
  • Reduce DOM depth

Q8: Storage mechanisms

FeaturelocalStoragesessionStorageCookies
Capacity~5-10MB~5-10MB~4KB
ExpirationPersistentTab closeConfigurable
Server accessNoNoSent with every request
ScopeSame originSame tab and originConfigurable path

Use cases:

  • localStorage: User preferences, cached data
  • sessionStorage: Temporary form data, session state
  • Cookies: Authentication tokens, server-side session tracking

Q9: CORS (Cross-Origin Resource Sharing)

CORS is a browser security mechanism that controls cross-origin HTTP requests.

Same-origin policy: Two URLs have the same origin if they share the same protocol, host, and port.

CORS flow:

  1. Browser sends request with Origin header
  2. Server responds with Access-Control-Allow-Origin header
  3. Browser allows response if origins match or wildcard is specified

Preflight requests (OPTIONS):

  • Required for non-simple requests (non-GET, custom headers)
  • Browser checks permissions before sending actual request

Q10: HTTP caching

Request headers:

HeaderPurpose
Cache-Control: no-cacheRevalidate before using cached response
If-Modified-SinceConditional request based on modification date
If-None-MatchConditional request based on ETag

Response headers:

HeaderPurpose
Cache-Control: max-age=3600Cache for 1 hour
ETagVersion identifier for validation
Last-ModifiedTimestamp of last modification

Cache hierarchy: Browser cache, CDN, Origin server

Best practice: Use long cache durations for static assets with content hashing in filenames for cache busting.

React

Q11: Virtual DOM

The Virtual DOM is an in-memory representation of the actual DOM.

Reconciliation process:

  1. State change triggers new Virtual DOM tree creation
  2. React diffs new tree against previous tree
  3. Minimal set of DOM operations calculated
  4. Batch updates applied to actual DOM

Benefits:

BenefitDescription
PerformanceBatched updates reduce DOM manipulation
Declarative modelDescribe UI state, React handles updates
Cross-platformSame model enables React Native

Q12: Rules of Hooks

Two rules govern React Hooks usage:

RuleReason
Only call at top levelReact tracks hooks by call order
Only call from React functionsMust be in function components or custom hooks

Incorrect pattern: Calling a hook inside a conditional statement means the hook may not be called on some renders, breaking React's tracking mechanism.

Correct pattern: Call hooks unconditionally at the top level, then use conditional logic after the hook call to determine how to use the returned values.

React relies on consistent hook call order between renders. Conditional hook calls break this ordering.

Q13: useEffect vs useLayoutEffect

HookTimingBlocking
useEffectAfter paint, asynchronousNo
useLayoutEffectAfter DOM update, before paintYes

Use useLayoutEffect when:

  • Measuring DOM elements (getBoundingClientRect)
  • Preventing visual flashes from synchronous DOM updates
  • Reading layout and synchronously re-rendering

Use useEffect for most cases unless visual flickering occurs.

Q14: Reconciliation algorithm

React's reconciliation determines DOM updates through these rules:

ScenarioBehavior
Different element typesReplace entire subtree
Same element typeKeep node, update changed attributes
Component updateRe-render, recursively check children
ListsMatch items using keys

Keys in lists:

Key StrategyBehavior
Without keysCompare by index (fails on reorder)
With stable keysEfficient matching of old and new items

Use stable, unique keys. Array indices cause incorrect behavior when items are reordered, added, or removed.

Q15: React performance optimization

Preventing unnecessary renders:

TechniquePurpose
React.memoMemoize component based on props
useMemoMemoize computed values
useCallbackMemoize callback functions

Code splitting:

TechniquePurpose
React.lazyDynamic component imports
SuspenseLoading states for lazy components
Route-based splittingLoad code per route

Virtualization:

  • react-window, react-virtualized
  • Render only visible items in long lists

State management:

  • Keep state close to where it is used
  • Avoid unnecessary global state

Profiling:

  • React DevTools Profiler
  • Identify components with wasted renders

Performance

Q16: Core Web Vitals

MetricMeasurementTarget
LCP (Largest Contentful Paint)Loading performance< 2.5s
INP (Interaction to Next Paint)Responsiveness< 200ms
CLS (Cumulative Layout Shift)Visual stability< 0.1

Optimization strategies:

MetricTechniques
LCPOptimize images, use CDN, preload critical resources
INPReduce JavaScript execution, break up long tasks
CLSSet explicit dimensions on images, avoid dynamic content injection

Q17: Lazy loading and code splitting

Lazy loading: Defer loading resources until needed.

TypeImplementation
Imagesloading="lazy" attribute
ComponentsLoad on route navigation or user interaction
DataLoad on scroll or interaction

Code splitting: Divide application bundle into smaller chunks.

React lazy loading: Use React.lazy with a dynamic import to load components on demand. The component is loaded only when it is first rendered.

Route-based splitting: Configure routes to use lazy-loaded components, so each route's code is loaded only when the user navigates to that route.

Benefits: Faster initial load, reduced initial bundle size.

Q18: Bundle size reduction

StrategyDescription
AnalysisUse webpack-bundle-analyzer to identify large dependencies
Tree shakingRemove unused exports during build
Code splittingLazy load routes and components
Dynamic importsLoad libraries on demand
Library selectionUse lighter alternatives (date-fns vs moment)
CompressionEnable gzip or Brotli compression
Modern syntaxServe ES6+ to modern browsers

Q19: Service workers

A service worker is a JavaScript file that runs in a separate thread from the main page.

Capabilities:

FeatureDescription
Offline supportCache assets and data for offline access
Push notificationsReceive notifications when tab is closed
Background syncDefer actions until network is available

Lifecycle:

  1. Register
  2. Install (cache assets)
  3. Activate (take control of pages)
  4. Fetch events (intercept network requests)

Service workers enable Progressive Web App (PWA) functionality.

Q20: Debounce vs throttle

Both limit function execution frequency.

TechniqueBehaviorUse Case
DebounceExecute after activity stops for specified durationSearch input (wait for typing to stop)
ThrottleExecute at most once per time periodScroll handler (update at fixed intervals)

Debounce example: Wrap a search function with a 300ms debounce. The search executes only after the user stops typing for 300ms.

Throttle example: Wrap a scroll handler with a 100ms throttle. The handler executes at most once every 100ms during scrolling.