Top 100 frontend interview questions and answers, covering HTML, CSS, JavaScript, React, and more. It’s designed to help you prepare for your next frontend developer interview with practical, concise, and accurate answers.
HTML Questions
1. What is the purpose of the <!DOCTYPE html>
declaration?
The <!DOCTYPE html>
declaration at the start of an HTML document informs browsers that the document is written in HTML5. It ensures the browser renders the page in standards mode, adhering to modern web standards.
2. What are semantic HTML elements?
Semantic HTML elements (e.g., <header>
, <footer>
, <article>
, <section>
) clearly describe their meaning to both browsers and developers. They improve accessibility, SEO, and code readability compared to non-semantic elements like <div>
.
3. What is the difference between <div>
and <section>
?
A <div>
is a generic container with no semantic meaning, used for styling or grouping. A <section>
is a semantic element representing a standalone section of content, typically with a heading, and conveys meaning to assistive technologies.
4. What is the alt
attribute in an <img>
tag?
The alt
attribute provides alternative text for an image, used by screen readers for accessibility or displayed if the image fails to load. It should describe the image’s purpose or content, e.g., alt="Company logo"
.
5. What are HTML data attributes?
Data attributes (e.g., data-*
) allow developers to store custom data in HTML elements. They are accessible via JavaScript (element.dataset
) and are useful for attaching metadata without affecting presentation, e.g., <div data-id="123">
.
6. What is the difference between id
and class
attributes?
An id
is a unique identifier for a single element, while a class
can be applied to multiple elements for shared styling or behavior. Use id
for unique elements (e.g., #header
) and class
for reusable styles (e.g., .button
).
7. What is the purpose of the <meta>
tag?
The <meta>
tag provides metadata about the HTML document, such as character encoding (<meta charset="UTF-8">
), viewport settings (<meta name="viewport" content="width=device-width, initial-scale=1.0">
), or SEO information (e.g., <meta name="description" content="Site description">
).
8. What is the difference between inline and block elements?
Block elements (e.g., <div>
, <p>
) start on a new line and take up the full width available. Inline elements (e.g., <span>
, <a>
) sit within the flow of text and only take up the space of their content.
9. What is the HTML5 canvas
element used for?
The <canvas>
element provides a resolution-dependent bitmap surface for rendering graphics, animations, or games using JavaScript. It’s commonly used with APIs like WebGL or the 2D rendering context.
10. What is the purpose of the aria-*
attributes?
ARIA (Accessible Rich Internet Applications) attributes (e.g., aria-label
, aria-hidden
) enhance accessibility by providing additional context to assistive technologies, especially for dynamic content or non-semantic elements.
CSS Questions
11. What is the CSS Box Model?
The CSS Box Model describes the rectangular boxes generated for elements, consisting of content, padding, border, and margin. The total size of an element includes all these layers, affecting layout and spacing.
12. What is the difference between relative
, absolute
, fixed
, and sticky
positioning?
relative
: Positioned relative to its normal position.absolute
: Positioned relative to the nearest positioned ancestor or the document body.fixed
: Positioned relative to the viewport, stays in place on scroll.sticky
: Toggles betweenrelative
andfixed
, sticking within its parent during scroll.
13. What is a CSS pseudo-class?
A pseudo-class (e.g., :hover
, :focus
, :nth-child
) targets elements based on their state or position. For example, a:hover
styles a link when the mouse hovers over it.
14. What is the difference between flex
and grid
layouts?
Flexbox is a one-dimensional layout for arranging items in rows or columns, ideal for linear layouts. CSS Grid is a two-dimensional system for creating complex layouts with rows and columns, offering more control over both axes.
15. What is the z-index
property?
The z-index
property controls the stacking order of positioned elements. Higher z-index
values place elements in front of those with lower values. It only works on elements with position: absolute
, relative
, or fixed
.
16. What is the difference between rem
and em
units?
rem
: Relative to the root (<html>
) font size (e.g.,1rem
=16px
if the root font size is16px
).em
: Relative to the font size of the parent element, which can lead to compounding effects in nested elements.
17. What is a CSS media query?
A media query applies styles based on conditions like screen size, resolution, or device type (e.g., @media (max-width: 600px) { ... }
). It’s essential for responsive design.
18. What is the purpose of the box-sizing
property?
The box-sizing
property defines how the width and height of an element are calculated. content-box
(default) includes only content, while border-box
includes padding and border, simplifying sizing calculations.
19. What are CSS custom properties (variables)?
CSS custom properties (e.g., --primary-color: #007bff
) allow reusable values in CSS. Defined with --
and accessed with var()
, they simplify maintenance and theming, e.g., color: var(--primary-color)
.
20. What is the ::before
and ::after
pseudo-elements?
::before
and ::after
create virtual elements before or after an element’s content. They’re often used for decorative purposes, like adding icons or styling, requiring the content
property.
JavaScript Questions
21. What is the difference between var
, let
, and const
?
var
: Function-scoped, hoisted, can be redeclared and reassigned.let
: Block-scoped, not hoisted, can be reassigned but not redeclared in the same scope.const
: Block-scoped, not hoisted, cannot be reassigned or redeclared, but object properties can be mutated.
22. What is closure in JavaScript?
A closure is a function that retains access to its lexical scope’s variables even after the outer function has finished executing. It’s useful for data privacy and creating function factories.
23. What is the difference between null
and undefined
?
null
: Represents an intentional absence of value, explicitly set by the developer.undefined
: Indicates a variable has been declared but not assigned a value or is inaccessible.
24. What is event delegation?
Event delegation involves attaching a single event listener to a parent element to handle events from its children, leveraging event bubbling. It improves performance and handles dynamically added elements.
25. What is the this
keyword in JavaScript?
The this
keyword refers to the context in which a function is executed. Its value depends on how the function is called (e.g., global object in non-strict mode, undefined
in strict mode, or the object in methods).
26. What is the difference between ==
and ===
?
==
: Loose equality, compares values after type coercion (e.g.,5 == "5"
istrue
).===
: Strict equality, compares values and types without coercion (e.g.,5 === "5"
isfalse
).
27. What is a Promise in JavaScript?
A Promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: pending
, fulfilled
, or rejected
, and is used with .then()
, .catch()
, or async/await
.
28. What is the purpose of async
and await
?
async
declares a function that returns a Promise. await
pauses the execution of an async
function until the Promise resolves, making asynchronous code easier to read and write.
29. What is the event loop in JavaScript?
The event loop manages asynchronous operations by processing the call stack and task queue. It ensures non-blocking behavior by executing callbacks (e.g., from setTimeout
or Promises) when the stack is empty.
30. What is the difference between forEach
and map
?
forEach
: Iterates over an array and executes a callback for each element, with no return value.map
: Iterates over an array, applies a callback to each element, and returns a new array with the results.
React Questions
31. What is React, and why use it?
React is a JavaScript library for building user interfaces, particularly single-page applications, using a component-based architecture. It’s fast, scalable, and simplifies state management and DOM updates via a virtual DOM.
32. What is the virtual DOM?
The virtual DOM is an in-memory representation of the real DOM. React uses it to track changes, compute minimal updates, and efficiently apply them to the actual DOM, improving performance.
33. What are React components?
Components are reusable building blocks in React, either functional (stateless) or class-based (stateful). They accept props and return JSX to describe the UI, e.g., function Button({ label }) { return <button>{label}</button>; }
.
34. What is the difference between props and state?
- Props: Immutable data passed from a parent to a child component.
- State: Mutable data managed within a component, updated using
setState
(class) oruseState
(functional).
35. What is the useState
hook?
The useState
hook is a React Hook that adds state to functional components. It returns a state variable and a setter function, e.g., const [count, setCount] = useState(0)
.
36. What is the useEffect
hook?
The useEffect
hook handles side effects (e.g., data fetching, subscriptions) in functional components. It runs after render and can clean up with a return function, e.g., useEffect(() => { ... }, [dependencies])
.
37. What is JSX?
JSX is a syntax extension for JavaScript that allows writing HTML-like code in React. It’s transpiled to JavaScript (e.g., React.createElement
) by tools like Babel.
38. What is a controlled component in React?
A controlled component is a form element whose value is controlled by React state. For example, an <input>
with value
and onChange
tied to a state variable ensures predictable behavior.
39. What is the purpose of key
in React lists?
The key
prop uniquely identifies elements in a list, helping React efficiently update the DOM by tracking which items have changed, added, or removed.
40. What is React Router?
React Router is a library for handling client-side routing in React applications. It enables navigation between components without page reloads, using components like <BrowserRouter>
and <Route>
.
General Frontend Questions
41. What is the difference between synchronous and asynchronous code?
Synchronous code executes sequentially, blocking further execution until complete. Asynchronous code (e.g., setTimeout
, Promises) runs non-blocking, allowing other tasks to proceed while waiting.
42. What is CORS?
Cross-Origin Resource Sharing (CORS) is a security mechanism that restricts or allows requests to a different domain. It uses HTTP headers to define which origins, methods, and headers are permitted.
43. What is the purpose of a CDN?
A Content Delivery Network (CDN) delivers web content (e.g., images, scripts) from servers geographically closer to users, reducing latency and improving performance.
44. What is responsive design?
Responsive design ensures a website adapts to different screen sizes and devices using techniques like fluid grids, flexible images, and media queries.
45. What is the difference between localStorage
and sessionStorage
?
localStorage
: Persists data until explicitly cleared, shared across browser tabs.sessionStorage
: Persists data only for the duration of a tab’s session, cleared when the tab closes.
46. What is a single-page application (SPA)?
An SPA is a web app that loads a single HTML page and dynamically updates content using JavaScript, avoiding full page reloads. Examples include apps built with React or Vue.
47. What is progressive enhancement?
Progressive enhancement is a strategy where a basic functional version of a site is built first (e.g., HTML/CSS), then enhanced with JavaScript for better interactivity, ensuring accessibility for all users.
48. What is the purpose of defer
and async
attributes in a <script>
tag?
defer
: Loads the script asynchronously but executes it after the DOM is fully parsed.async
: Loads and executes the script asynchronously, potentially out of order.
49. What is Web Accessibility (a11y)?
Web accessibility ensures websites are usable by people with disabilities, following standards like WCAG. Techniques include semantic HTML, ARIA, and keyboard navigation support.
50. What is the purpose of a CSS reset?
A CSS reset removes default browser styles (e.g., margins, paddings) to ensure consistent rendering across browsers, providing a clean slate for custom styles.
Advanced Questions
51. What is a closure leak, and how do you prevent it?
A closure leak occurs when a closure unintentionally retains references to large objects, preventing garbage collection. Prevent it by nullifying references or using weak references (e.g., WeakMap
).
52. What is tree shaking in JavaScript?
Tree shaking is a bundler optimization (e.g., in Webpack) that removes unused code from the final bundle, reducing file size and improving performance.
53. What is the difference between shallow and deep copying?
- Shallow copy: Copies only the top-level properties of an object, sharing references to nested objects (e.g.,
Object.assign
). - Deep copy: Creates a fully independent copy of an object, including nested objects (e.g.,
JSON.parse(JSON.stringify(obj))
).
54. What is the purpose of the IntersectionObserver
API?
The IntersectionObserver
API monitors an element’s visibility within an ancestor or viewport, enabling lazy loading, infinite scrolling, or triggering animations when elements enter the view.
55. What is memoization in JavaScript?
Memoization is an optimization technique that caches function results based on input parameters, avoiding redundant computations. It’s commonly used for expensive calculations.
56. What is the difference between SSR, CSR, and SSG?
- Server-Side Rendering (SSR): Renders HTML on the server for each request (e.g., Next.js).
- Client-Side Rendering (CSR): Renders HTML in the browser using JavaScript (e.g., React).
- Static Site Generation (SSG): Pre-renders HTML at build time (e.g., Gatsby).
57. What is the purpose of the useMemo
hook in React?
The useMemo
hook memoizes expensive computations, recomputing only when dependencies change. It optimizes performance by preventing unnecessary recalculations.
58. What is a service worker?
A service worker is a script that runs in the background, enabling features like offline support, push notifications, and caching for Progressive Web Apps (PWAs).
59. What is the difference between throttling and debouncing?
- Throttling: Limits function execution to a fixed interval (e.g., every 100ms).
- Debouncing: Delays function execution until a specified time has passed since the last call, useful for events like search input.
60. What is the requestAnimationFrame
API?
The requestAnimationFrame
API schedules animations to run before the next browser repaint, ensuring smooth and efficient animations compared to setInterval
.
Performance and Optimization
61. How can you optimize website performance?
- Minify CSS/JS files.
- Use lazy loading for images.
- Optimize images (e.g., use WebP format).
- Reduce HTTP requests.
- Leverage browser caching.
- Use a CDN.
62. What is lazy loading?
Lazy loading defers loading non-critical resources (e.g., images, scripts) until they’re needed, typically when they enter the viewport, improving initial page load time.
63. What is critical rendering path?
The critical rendering path is the sequence of steps browsers take to render a page (HTML parsing, CSSOM, DOM, render tree, layout, paint). Optimizing it reduces time to first paint.
64. How does browser caching work?
Browser caching stores resources (e.g., images, scripts) locally, reducing server requests on subsequent visits. Cache headers like Cache-Control
and ETag
control caching behavior.
65. What is code splitting?
Code splitting divides JavaScript bundles into smaller chunks, loading only what’s needed for the current view. It’s supported by tools like Webpack and improves load times.
66. What is the impact of reflows and repaints?
Reflows (layout recalculations) and repaints (visual updates) are triggered by DOM/CSS changes. Minimizing them (e.g., batching DOM updates, using transform
for animations) improves performance.
67. What is the purpose of a Content Security Policy (CSP)?
A CSP is a security layer that restricts the sources from which resources (e.g., scripts, images) can be loaded, mitigating risks like XSS attacks.
68. How do you optimize images for the web?
- Use modern formats like WebP or AVIF.
- Compress images without losing quality.
- Specify image dimensions in HTML/CSS.
- Use responsive images with
srcset
andsizes
.
69. What is the Lighthouse tool?
Lighthouse is a Google tool for auditing web performance, accessibility, SEO, and best practices. It provides scores and recommendations for improvement.
70. What is the impact of unused CSS?
Unused CSS increases file size, slows down parsing, and delays rendering. Tools like PurgeCSS or UnCSS remove unused styles to optimize performance.
Security Questions
71. What is Cross-Site Scripting (XSS)?
XSS is an attack where malicious scripts are injected into a website, executed in users’ browsers. Prevent it with input sanitization, escaping, and CSP.
72. What is Cross-Site Request Forgery (CSRF)?
CSRF tricks users into performing unintended actions on a site where they’re authenticated. Prevent it with CSRF tokens, same-site cookies, or validating origins.
73. How do you secure an API in a frontend application?
- Use HTTPS for encrypted communication.
- Implement authentication (e.g., OAuth, JWT).
- Validate and sanitize inputs.
- Use CORS to restrict origins.
- Avoid exposing sensitive data in client-side code.
74. What is the Same-Origin Policy?
The Same-Origin Policy restricts web pages from making requests to different origins (protocol, domain, port) unless explicitly allowed, enhancing security.
75. What are secure HTTP headers?
Secure headers like Strict-Transport-Security
, X-Content-Type-Options
, and Content-Security-Policy
enhance security by controlling browser behavior and mitigating attacks.
Miscellaneous Questions
76. What is TypeScript, and why use it?
TypeScript is a superset of JavaScript that adds static types. It improves code quality, catches errors early, and enhances tooling with features like autocompletion.
77. What is the purpose of a linter?
A linter (e.g., ESLint) analyzes code for errors, style issues, and best practices, ensuring consistency and reducing bugs in JavaScript and other languages.
78. What is Webpack?
Webpack is a module bundler that compiles JavaScript, CSS, and other assets into optimized bundles for the browser, supporting features like code splitting and tree shaking.
79. What is the difference between REST and GraphQL?
- REST: Uses multiple endpoints with fixed data structures, often over HTTP methods (GET, POST).
- GraphQL: Uses a single endpoint, allowing clients to request specific data with flexible queries.
80. What is a Progressive Web App (PWA)?
A PWA is a web app that uses modern APIs (e.g., service workers, manifests) to provide native-like experiences, including offline support, push notifications, and home screen installation.
Behavioral and Problem-Solving Questions
81. How do you approach debugging a frontend issue?
- Reproduce the issue consistently.
- Use browser dev tools to inspect elements, network, and console.
- Check for errors in JavaScript, CSS, or HTML.
- Isolate the issue using techniques like commenting code.
- Test fixes and verify across browsers/devices.
82. How do you ensure cross-browser compatibility?
- Use CSS resets or normalize.css.
- Test on multiple browsers (e.g., Chrome, Firefox, Safari).
- Use feature detection (e.g., Modernizr).
- Apply polyfills for unsupported features.
- Leverage tools like BrowserStack.
83. How do you handle state management in large React apps?
- Use state management libraries like Redux or Zustand for global state.
- Leverage React Context for simpler cases.
- Keep state close to where it’s used to avoid unnecessary complexity.
- Use hooks like
useReducer
for complex component state.
84. What is your approach to optimizing a slow React app?
- Use
React.memo
to prevent unnecessary re-renders. - Optimize with
useMemo
anduseCallback
for expensive computations. - Implement code splitting with dynamic imports.
- Profile performance with React DevTools.
- Reduce bundle size with tree shaking and lazy loading.
85. How do you stay updated with frontend trends?
- Follow blogs like CSS-Tricks, Smashing Magazine, or dev.to.
- Engage with communities on X or GitHub.
- Take online courses (e.g., Udemy, freeCodeCamp).
- Experiment with new tools and frameworks in side projects.
Coding Challenges
86. How would you reverse a string in JavaScript?
function reverseString(str) {
return str.split('').reverse().join('');
}
87. How do you check if a number is a palindrome?
function isPalindrome(num) {
return num.toString() === num.toString().split('').reverse().join('');
}
88. How do you implement a debounce function?
function debounce(func, delay) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func(...args), delay);
};
}
89. How do you create a counter component in React?
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
90. How do you fetch data in a React component?
import { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(setData)
.catch(console.error);
}, []);
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>;
}
Bonus Questions
91. What is the purpose of the useCallback
hook?
The useCallback
hook memoizes a function, preventing it from being recreated on every render unless dependencies change. It’s useful for passing stable callbacks to child components.
92. What is a CSS preprocessor?
A CSS preprocessor (e.g., Sass, Less) extends CSS with features like variables, nesting, and mixins, compiling to standard CSS for browser compatibility.
93. What is the Shadow DOM?
The Shadow DOM encapsulates a DOM subtree, isolating styles and markup from the main document. It’s used in web components to prevent style or script conflicts.
94. What is the difference between setTimeout
and setInterval
?
setTimeout
: Executes a function once after a specified delay.setInterval
: Repeatedly executes a function at a specified interval until cleared.
95. What is the purpose of the data-testid
attribute?
The data-testid
attribute is used for testing purposes, providing a stable identifier for elements in automated tests (e.g., with Jest or Cypress), avoiding reliance on fragile selectors.
96. What is a polyfill?
A polyfill is a script that provides modern functionality for older browsers that lack support. For example, Promise
or fetch
polyfills enable consistent APIs across browsers.
97. What is the difference between cookies and JWT?
- Cookies: Store data (e.g., session IDs) on the client, managed by the browser, often used for authentication.
- JWT (JSON Web Token): A self-contained token with encoded payload, used for stateless authentication, typically stored in
localStorage
or cookies.
98. What is the useReducer
hook in React?
The useReducer
hook manages complex state logic in functional components, using a reducer function to handle state transitions, similar to Redux.
99. What is the purpose of the rel
attribute in an <a>
tag?
The rel
attribute specifies the relationship between the current document and the linked resource. Common values include nofollow
(for SEO), noopener
(security), and noreferrer
(privacy).
100. How do you handle errors in async/await?
Use try/catch
to handle errors in async
functions:
async function fetchData() {
try {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
}
}