Here are 100 front‑end developer interview questions and answers, covering HTML, CSS, JavaScript, frameworks (React, Angular, Vue), performance, accessibility, tooling, and problem‑solving. Each question is in bold, followed by a detailed answer. No dividing lines.
What is the difference between HTML and HTML5?
Answer: HTML5 is the latest version of HTML, introducing new semantic elements (<article>, <section>, <nav>, <header>, <footer>), multimedia support (<audio>, <video>), canvas (<canvas>), local storage, and form input types (email, date, range). HTML5 also improved parsing rules and dropped support for deprecated elements like <font> or <center>.
What are semantic HTML elements and why are they important?
Answer: Semantic elements clearly describe their meaning to both the browser and the developer, such as <header>, <footer>, <article>, <section>, <nav>, <aside>. They improve accessibility (screen readers), SEO (search engines understand structure), and code maintainability. Non‑semantic elements like <div> and <span> provide no structural meaning.
Explain the CSS box model.
Answer: The box model describes how every element is rendered as a rectangular box consisting of: content (width/height), padding (space inside border), border, and margin (space outside border). The total width = width + left/right padding + left/right border + left/right margin. box-sizing: border-box changes the model so that width includes padding and border.
What is the difference between display: none and visibility: hidden?
Answer: display: none removes the element from the document layout – it takes no space and is not rendered. visibility: hidden hides the element visually but still occupies its original space in the layout, affecting the position of other elements.
What is the CSS position property and its possible values?
Answer: static (default – follows normal flow), relative (offset relative to its normal position), absolute (positioned relative to nearest positioned ancestor), fixed (relative to viewport, stays on scroll), sticky (switches between relative and fixed based on scroll). Sticky requires a threshold (top, left, etc.).
Explain the difference between inline, block, and inline-block display values.
Answer: block elements take full width, start on a new line, and accept width/height. inline elements take only as much width as needed, do not start new lines, and ignore width/height. inline-block elements are like inline but accept width/height and margins, yet sit on the same line if space permits.
What is Flexbox and when would you use it?
Answer: Flexbox (CSS Flexible Box Layout) is a one‑dimensional layout model for distributing space along a row or column. It excels at aligning items, controlling spacing, and creating responsive navigation bars, centering content vertically, equal‑height columns, and reordering items without HTML changes.
What is CSS Grid and how does it differ from Flexbox?
Answer: CSS Grid is a two‑dimensional layout system (rows and columns simultaneously), ideal for page‑wide layouts like dashboards, galleries, or magazine‑style designs. Flexbox is one‑dimensional (row or column) and best for aligning items inside containers. Grid controls both axes; Flexbox controls one axis.
What are CSS preprocessors (Sass, Less) and why are they useful?
Answer: Preprocessors extend CSS with variables, nested rules, mixins, functions, and modular files. They improve maintainability, reduce repetition, and allow logic (loops, conditionals). Sass (SCSS) is the most popular. Browsers still need compiled CSS, so tools like webpack or vite convert preprocessor code.
What is responsive design and how do you achieve it?
Answer: Responsive design ensures a website looks and works well on all devices and screen sizes. Techniques include: fluid grids (percentages), flexible images (max‑width: 100%), media queries (@media), viewport meta tag, and relative units (rem, vw, vh). Mobile‑first design (styles for small screens then larger using min-width) is a common approach.
What are CSS media queries and can you give an example?
Answer: Media queries apply CSS rules based on device characteristics like width, height, orientation, or resolution. Example:@media (max-width: 768px) { body { font-size: 14px; } }
This reduces font size on screens narrower than 768px.
Explain the concept of CSS specificity.
Answer: Specificity determines which CSS rule is applied when multiple rules target the same element. It is calculated as a four‑part score: inline styles (1000), IDs (100), classes/attributes/pseudo‑classes (10), elements/pseudo‑elements (1). The higher specificity wins. !important overrides all but is discouraged.
What is the z-index property and how does stacking context work?
Answer: z-index controls the stack order of positioned elements (non‑static). Higher z-index appears in front. A stacking context is a group of elements with a common parent. New stacking contexts are created by position: relative/absolute/fixed with a z-index value, opacity < 1, transform, filter, etc. Without a stacking context, z-index compares across the whole document.
What is the difference between a pseudo‑class and a pseudo‑element?
Answer: Pseudo‑classes (:hover, :focus, :nth-child) target a state of an existing element. Pseudo‑elements (::before, ::after, ::first-line) create virtual elements that are not part of the DOM. Use double colon (::) for pseudo‑elements (CSS3+).
What are CSS custom properties (CSS variables) and how do you use them?
Answer: CSS variables store values for reuse. Define with --custom-name: value; and access with var(--custom-name). They are scoped to the selector (e.g., :root for global) and can be updated dynamically with JavaScript, making them useful for theming and runtime changes.
What is the difference between rem and em units?
Answer: rem (root em) is relative to the root (<html>) font‑size. em is relative to the parent element’s font‑size. Using rem for spacing and typography ensures consistent scaling with the root setting, avoiding compounding issues common with em.
How do you center a div horizontally and vertically?
Answer: Several ways:
– Flexbox: display: flex; justify-content: center; align-items: center; on parent.
– Grid: display: grid; place-items: center; on parent.
– Absolute positioning + transform: position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); on the child.
– Margin auto for horizontal (block element with width) plus vertical centering with flex or grid.
What is the box-sizing property and why is it used?
Answer: box-sizing changes how width and height are calculated. box-sizing: border-box includes padding and border in the element’s total width/height, making layout easier and more predictable. Many frameworks set it globally: * { box-sizing: border-box; }.
Explain event delegation in JavaScript.
Answer: Event delegation attaches a single event listener to a parent element instead of multiple listeners on child elements. It leverages event bubbling to handle events from dynamically added children. Example: document.getElementById('parent').addEventListener('click', (e) => { if(e.target.matches('.child')) { /* handle */ } });. Improves performance and reduces memory usage.
What is the difference between == and === in JavaScript?
Answer: == (abstract equality) compares values after type coercion. === (strict equality) compares both value and type without coercion. Always use === to avoid unexpected bugs (e.g., 0 == false is true, 0 === false is false).
What is the event loop in JavaScript?
Answer: The event loop allows JavaScript, which is single‑threaded, to handle asynchronous operations. It continuously checks the call stack and the callback queue. When the stack is empty, it pushes callbacks from the queue onto the stack. This enables non‑blocking I/O, timers, promises, and event handling.
Explain var, let, and const differences.
Answer: var is function‑scoped or globally scoped, can be redeclared, and is hoisted with undefined value. let and const are block‑scoped, cannot be redeclared in the same scope, and are hoisted but not initialized (temporal dead zone). const must be assigned a value at declaration and cannot be reassigned (though object properties can be mutated).
What is a closure in JavaScript?
Answer: A closure is a function that retains access to its outer (enclosing) scope even after the outer function has returned. Closures are created every time a function is defined. They enable data privacy, currying, and module patterns. Example:function outer() { let x = 10; return function inner() { console.log(x); }; }
What is the this keyword in JavaScript and how is its value determined?
Answer: this is the context in which a function executes. Its value depends on how the function is called:
– In a method: refers to the object.
– Alone: in non‑strict mode, window (global); in strict mode, undefined.
– In an event handler: the element that received the event.
– Arrow functions: this is lexically inherited from the outer scope.
– Using call, apply, bind: explicitly set this.
What are arrow functions and how do they differ from regular functions?
Answer: Arrow functions (() => {}) have a shorter syntax, do not have their own this, arguments, super, or new.target. They are always anonymous and cannot be used as constructors (no new). Their this is lexically bound to the surrounding scope, making them ideal for callbacks.
Explain promises in JavaScript.
Answer: Promises represent the eventual completion (or failure) of an asynchronous operation. A promise is in one of three states: pending, fulfilled (resolved), or rejected. Methods: .then() for success, .catch() for error, .finally() for cleanup. Promises allow chaining, avoid callback hell, and work with async/await.
What is async/await and how does it relate to promises?
Answer: async functions return a promise. await pauses the execution of the async function until the awaited promise settles, then resumes with the resolved value. It provides a synchronous‑looking syntax for promise‑based code, simplifying error handling with try/catch. await can only be used inside an async function.
What is the difference between null and undefined?
Answer: undefined is the default value for uninitialized variables, missing object properties, and function parameters without arguments. null is an intentional absence of any object value, often assigned by developers. undefined is a type, null is an object (historical bug). Use == null to check for either.
What is the Document Object Model (DOM)?
Answer: The DOM is a programming interface (tree‑like structure) for HTML/XML documents. It represents the page so that programs can change the document structure, style, and content. JavaScript can access and manipulate the DOM via objects like document, element, node.
What is the difference between localStorage, sessionStorage, and cookies?
Answer: All store data on the client side. localStorage persists across browser sessions (no expiration). sessionStorage lasts only for the current tab/session. Both store up to ~5‑10MB and are not sent to the server automatically. Cookies are smaller (4KB), have expiration dates, and are sent with every HTTP request, affecting performance. Use localStorage for client‑only data, cookies for server‑side reading or authentication tokens.
Explain the concept of hoisting in JavaScript.
Answer: Hoisting moves variable and function declarations to the top of their containing scope during compilation. var variables are hoisted and initialized with undefined. let and const are hoisted but not initialized (temporal dead zone). Function declarations are hoisted completely, so they can be called before definition.
What is the map() method in arrays?
Answer: map() creates a new array by applying a callback function to each element of the original array. It does not mutate the original array. Example: [1,2,3].map(x => x * 2) // [2,4,6]. It is chainable and ideal for transformations.
What are the differences between forEach, map, and reduce?
Answer: forEach iterates over array elements, returns undefined, and mutates or does side effects. map returns a new transformed array of the same length. reduce accumulates a single value from an array, using a reducer function and an initial value. Choose based on need: map for transformation, reduce for aggregation, forEach for side effects.
How does prototypal inheritance work in JavaScript?
Answer: Every JavaScript object has an internal [[Prototype]] (accessed via __proto__ or Object.getPrototypeOf()). When accessing a property, the engine first looks at the object itself, then follows the prototype chain upwards until found or null. Functions have a prototype property used when called with new. This enables object‑oriented patterns without classical classes.
What is the difference between Object.assign() and the spread operator?
Answer: Both create shallow copies. Object.assign(target, ...sources) modifies the target object and returns it. The spread operator { ...obj } creates a new object without modifying the original. For merging, spread is more concise and safer against accidental mutation.
What is a pure function?
Answer: A pure function always returns the same output for the same input and has no side effects (does not modify external state, no I/O). Pure functions are predictable, testable, and cacheable. They are a core concept in functional programming and help with React hooks, Redux reducers.
Explain the concept of debouncing and throttling.
Answer: Debouncing delays function execution until after a certain idle time (e.g., search input stops typing for 300ms). Throttling limits function execution to at most once per specified interval (e.g., scroll event handlers). Both improve performance for events like resize, scroll, input.
What is the difference between call, apply, and bind?
Answer: call invokes a function with a given this value and arguments passed individually. apply is similar but arguments are passed as an array. bind returns a new function with a bound this and optional preset arguments, without invoking immediately. They are used to control context explicitly.
How do you handle asynchronous errors in promises?
Answer: Attach a .catch() block at the end of the promise chain, or use try/catch with async/await. For multiple promises, use Promise.allSettled() to handle failures individually, or Promise.all() fails fast. Global unhandled rejections can be caught with window.addEventListener('unhandledrejection').
What is the fetch API and how does it differ from XMLHttpRequest?
Answer: fetch() is a modern, promise‑based API for making HTTP requests. It provides a more powerful and flexible feature set than XMLHttpRequest (XHR). fetch does not automatically reject on HTTP error statuses (like 404 or 500), only on network failures. It returns a promise that resolves to a Response object. XHR is callback‑based and older.
What is the purpose of use strict?
Answer: 'use strict' enables strict mode, which catches common coding errors, prevents accidental globals, eliminates with, forbids duplicate parameter names, changes this behavior in functions to undefined instead of global, and throws more exceptions. It improves security and performance. Use at top of script or function.
What is the difference between an attribute and a property in DOM?
Answer: Attributes are defined in HTML markup (e.g., class="btn"). Properties are properties of the DOM object (e.g., element.className). When the page loads, some attributes are reflected as properties, but they can diverge. value property of an input reflects current value; value attribute reflects initial value. Use setAttribute/getAttribute for attributes, dot notation for properties.
What are Web Workers and when should you use them?
Answer: Web Workers run JavaScript in background threads separate from the main execution thread, allowing heavy computations without blocking the UI. They cannot access the DOM directly. Use them for image processing, large data sorting, crypto operations, or any CPU‑intensive task.
What is the Virtual DOM and how does it work?
Answer: The Virtual DOM is a lightweight JavaScript object representation of the real DOM, used by frameworks like React. When state changes, a new virtual DOM tree is created and diffed against the previous one. Only the minimal set of changes is applied to the real DOM via a reconciliation algorithm. This improves performance by batching updates and reducing direct DOM manipulation.
Explain React’s component lifecycle (classes) and how it maps to hooks.
Answer: In class components: componentDidMount (after first render), componentDidUpdate (after updates), componentWillUnmount (before removal). In functional components with hooks: useEffect(() => { ... }, []) mimics componentDidMount. useEffect(() => { ... }, [deps]) mimics componentDidUpdate. The cleanup function in useEffect mimics componentWillUnmount.
What is the useEffect hook and how does it work?
Answer: useEffect performs side effects in function components (data fetching, subscriptions, manual DOM changes). It runs after render. Accepts a function and an optional array of dependencies. Re‑runs when any dependency changes. An empty dependency array [] runs only on mount. The returned cleanup function runs before unmount and before the next effect.
What is state in React and how is it managed?
Answer: State is data that changes over time and affects what is rendered. In class components, state is managed with this.state and this.setState(). In functional components, useState hook returns a state variable and a setter. For global state, use Context API or third‑party libraries like Redux, Zustand, or Recoil.
What is the difference between props and state?
Answer: Props (properties) are read‑only data passed from parent to child component. State is internal, mutable data managed within a component. Props are immutable; state can be updated with setter functions.
What are React hooks?
Answer: Hooks are functions that let developers “hook into” React features (state, lifecycle, context) from functional components without writing classes. Common hooks: useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef. Hooks must be called at the top level of a component, not conditionally.
Explain the significance of keys in React lists.
Answer: Keys help React identify which items have changed, been added, or removed. They should be stable, unique, and predictable (e.g., item IDs). Using array indices as keys is discouraged because they change when items reorder, causing unnecessary re‑renders and potential bugs.
What is the use of useRef hook?
Answer: useRef returns a mutable ref object whose .current property persists for the component’s lifetime. It does not cause re‑renders when changed. Use it to access DOM elements directly (e.g., focus management), store previous values, or keep mutable instance variables.
What is the difference between controlled and uncontrolled components in React?
Answer: Controlled components have form input values controlled by React state via value and onChange props. Uncontrolled components store their own state in the DOM, accessed via ref. Controlled components are recommended because they give more control, validation, and dynamic updates.
What is the Context API in React and when would you use it?
Answer: Context provides a way to pass data through the component tree without prop drilling. Use it for global states like theme, authentication, language, etc. Create context with createContext(), provide with <Provider>, consume with useContext(Context) or <Context.Consumer>. Not ideal for high‑frequency updates (use state management like Redux then).
What is React Router and how does it work?
Answer: React Router is a standard library for routing in React applications. It enables navigation between components without page reload. Core components: <BrowserRouter>, <Routes>, <Route>, <Link>, <Outlet>. It uses the browser’s URL and provides declarative routing.
Explain what Redux is and its core principles.
Answer: Redux is a predictable state container for JavaScript apps. Core principles: single source of truth (store), state is read‑only (actions), changes are made with pure reducer functions (previous state + action = new state). It uses a central store, action creators, dispatch, and selectors. Often used with React via React‑Redux.
What is the difference between server‑side rendering (SSR) and client‑side rendering (CSR)?
Answer: SSR renders the full HTML for a page on the server and sends it to the browser, improving SEO and initial load time but potentially slower interactivity. CSR sends a minimal HTML with JavaScript; the browser renders the page client‑side, which can be faster after the first load but may hurt SEO and time‑to‑first‑paint. Frameworks like Next.js (React) and Nuxt.js (Vue) support SSR.
What is a progressive web app (PWA)?
Answer: A PWA is a web application that uses modern APIs to deliver an app‑like experience (offline support, push notifications, home screen installation, fast loading). Key components: service workers for caching, Web App Manifest for metadata, and HTTPS. PWAs bridge the gap between web and native mobile apps.
What is a service worker and what can it do?
Answer: A service worker is a script that runs in the background, separate from the web page, enabling features like offline support, push notifications, background sync, and network interception (fetch events). It acts as a proxy between the browser and the network.
What is webpack and why is it used?
Answer: Webpack is a module bundler for JavaScript applications. It takes modules with dependencies and generates static assets by bundling, minifying, transpiling (via loaders), and optimizing (via plugins). It supports code splitting, hot module replacement, and asset management (CSS, images, fonts).
What are the differences between npm and yarn?
Answer: Both are package managers for Node.js. Yarn was created by Facebook to address performance and security issues in npm. Key differences: Yarn uses yarn.lock, npm uses package‑lock.json; Yarn parallel installations (faster), npm sequential; Yarn has offline cache by default. Modern npm versions have improved speed and parity.
What is a CSS‑in‑JS solution?
Answer: CSS‑in‑JS is a technique where styles are written in JavaScript and scoped to components (e.g., styled‑components, Emotion). Benefits: dynamic theming, scoped styles (no global conflicts), better code splitting, and easier deletion of unused styles. Downside: runtime performance overhead.
Explain the concept of accessibility (a11y) in front‑end development.
Answer: Accessibility ensures that websites are usable by people with disabilities (visual, auditory, motor, cognitive). Practices: semantic HTML, ARIA attributes, keyboard navigation (tabindex), sufficient color contrast, alt text for images, captioning for video, focus management, and testing with screen readers (NVDA, VoiceOver). Following WCAG guidelines is essential.
What is ARIA and when would you use it?
Answer: ARIA (Accessible Rich Internet Applications) provides attributes to enhance accessibility when native HTML cannot achieve the desired semantics. Use ARIA roles (role="button"), properties (aria‑label, aria‑expanded), and states (aria‑disabled). Rule: use native HTML first; ARIA only as a fallback.
How do you optimize website performance (loading speed)?
Answer: Techniques: minify CSS/JS/HTML, lazy load images and iframes, compress images (WebP, AVIF), use CDN, enable browser caching, reduce render‑blocking resources, code splitting, tree shaking, defer JavaScript, use <link rel="preload">, optimize fonts, and audit with Lighthouse.
What is tree shaking and how does it work?
Answer: Tree shaking is a dead‑code elimination technique used by module bundlers (webpack, Rollup). It relies on ES2015 module syntax (import/export). Bundlers analyze static imports and exclude unused exports from the final bundle, reducing file size.
What is the difference between cookie, sessionStorage, and localStorage?
Answer: (Already covered earlier – but for completeness) Cookies (4KB, sent with requests), sessionStorage (per‑tab, cleared on close), localStorage (persists, cross‑tab). Use localStorage for client‑only data, sessionStorage for sensitive one‑session data, cookies for authentication tokens that need server access.
Explain cross‑site scripting (XSS) and how to prevent it.
Answer: XSS occurs when an attacker injects malicious scripts into web pages viewed by others. Prevention: sanitize user input, escape output (use textContent instead of innerHTML), use Content Security Policy (CSP) headers, and avoid eval() and innerHTML with user data.
What is the difference between localStorage and IndexedDB?
Answer: localStorage stores key‑value pairs synchronously with a 5‑10MB limit, only strings. IndexedDB is an asynchronous NoSQL database for larger amounts of structured data (blobs, files), supporting indexes, queries, and transactions. Use IndexedDB for offline apps, large datasets, or complex querying.
How do you handle responsive images?
Answer: Use the <picture> element with multiple <source> tags for different resolutions/art direction, or srcset and sizes attributes on <img> to serve appropriately sized images based on viewport width. CSS media queries can also change background‑image.
What is the defer and async attribute on <script> tags?
Answer: async downloads the script asynchronously and executes it immediately after download, without blocking HTML parsing. defer also downloads asynchronously but executes only after the HTML is fully parsed, preserving order. Defer is generally safer for scripts that depend on DOM.
What is the contenteditable attribute?
Answer: contenteditable="true" makes an HTML element editable by the user. It is useful for rich text editors, notes, and inline editing. It triggers input events and can be manipulated with document.execCommand() (deprecated) or modern APIs.
What is event bubbling and capturing?
Answer: Event propagation has three phases: capturing (from window to target), target, bubbling (from target back to window). By default, event handlers listen on the bubbling phase. addEventListener has a useCapture parameter to enable capturing. stopPropagation() prevents further bubbling/capturing.
What is the difference between stopPropagation and stopImmediatePropagation?
Answer: stopPropagation() prevents further propagation (bubbling or capturing) but allows other listeners on the same element to fire. stopImmediatePropagation() also prevents other listeners on the same element from being called, stopping any remaining handlers.
Explain the concept of memoization and its use in React.
Answer: Memoization caches the results of expensive function calls based on inputs. In React, React.memo for components, useMemo for values, and useCallback for functions help prevent unnecessary re‑renders when dependencies haven’t changed, improving performance.
What is a higher‑order component (HOC)?
Answer: An HOC is a function that takes a component and returns a new component with added props or behavior. It’s a pattern for reusing component logic (e.g., authentication, logging). Example: const EnhancedComponent = withAuth(MyComponent);. Hooks now often replace HOCs.
What is the useReducer hook and when to use it over useState?
Answer: useReducer is an alternative to useState for complex state logic that involves multiple sub‑values or when the next state depends on the previous one (like a counter). It’s ideal for state transition patterns (e.g., Redux‑like reducers). Use it when you have state transitions that are complex or many related actions.
What are web components?
Answer: Web Components are a set of browser standards (Custom Elements, Shadow DOM, HTML Templates) that allow developers to create reusable, encapsulated custom HTML elements without a framework. They work across frameworks and vanilla JS.
What is the Shadow DOM?
Answer: Shadow DOM allows encapsulation of a subtree of DOM elements, isolated from the main document’s CSS and JavaScript. It enables component scoping (styles don’t leak out, scripts don’t interfere). Used in Web Components and some frameworks internally.
How do you debug JavaScript performance issues?
Answer: Use Chrome DevTools: Performance tab to record runtime, flame charts, and identify long tasks. Use Memory tab to detect leaks. Use Lighthouse for overall audits. Use console.time() and performance.now() for micro‑benchmarks. React DevTools, Vue DevTools help with component re‑renders.
What is the purpose of the role attribute?
Answer: The role attribute defines the purpose of an element to assistive technologies (screen readers), especially when native semantics are overridden or custom widgets are created (e.g., role="button" on a <div>). Use native HTML first; roles are a fallback.
What are meta tags and give examples of important ones.
Answer: <meta> tags provide metadata about the HTML document. Examples: <meta charset="UTF-8">, <meta name="viewport" content="width=device-width, initial-scale=1">, <meta name="description" content="...">, <meta name="robots" content="noindex">, <meta property="og:title" content="..."> for social media.
What is the difference between a <button> and an <input type="button">?
Answer: <button> can contain HTML content (icons, images) and has better styling flexibility. <input type="button"> has limited content (only text). Both trigger JavaScript actions. Use <button> for better accessibility and semantics unless you need a reset/submit in forms (which have specific types).
Explain what the doctype declaration does.
Answer: <!DOCTYPE html> tells the browser which version of HTML to expect, triggering standards mode instead of quirks mode. In HTML5, the doctype is simple and case‑insensitive. Without it, browsers may misinterpret CSS and layout.
What are data attributes?
Answer: Data attributes (e.g., data‑my‑value="123") store custom data on HTML elements without affecting styling or script. Access via element.dataset.myValue (camelCase). Useful for storing state or configuration.
How do you center text both horizontally and vertically in CSS?
Answer: Flexbox: display: flex; justify-content: center; align-items: center; on parent. For single line text, line-height equal to container height works horizontally (vertical only if text wraps?). Or display: grid; place-items: center.
What are @keyframes in CSS?
Answer: @keyframes define animations by specifying styles at various percentages (0% to 100%) or using from/to. Apply animation with the animation property (name, duration, iteration count, etc.). Example: @keyframes slide { from { transform: translateX(0); } to { transform: translateX(100px); } }.
What is the difference between transition and animation?
Answer: Transitions are used to smoothly change property values over a duration, triggered by state changes (e.g., :hover). They only have start and end states. Animations are more complex and can have multiple keyframes, loop, and run automatically without a trigger.
Explain the purpose of requestAnimationFrame.
Answer: requestAnimationFrame schedules a function to run before the next browser repaint, allowing smooth animations. It is ideal for performance‑sensitive animations because it synchronizes with the refresh rate (typically 60fps) and pauses when the tab is inactive, saving CPU.
What is a SPA (Single Page Application)?
Answer: An SPA loads a single HTML page and dynamically updates content as the user interacts, without full page reloads. This provides a faster, app‑like experience. Frameworks like React, Angular, Vue are commonly used. Challenges include SEO (though SSR can help) and initial load time.
What are the differences between Angular, React, and Vue?
Answer: React is a library (UI layer) using JSX, unidirectional data flow, and virtual DOM, with a large ecosystem. Angular is a full‑framework (TypeScript, two‑way binding, dependency injection, RxJS). Vue is progressive, approachable, with single‑file components, virtual DOM, and a gentler learning curve. Each has strengths; React is most popular, Angular for enterprise, Vue for simplicity.
What is TypeScript and why would you use it?
Answer: TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds static types, interfaces, generics, and modern ES features. Benefits: early error detection, better IDE support (autocomplete, refactoring), improved code maintainability and documentation, especially in large codebases.
What is GraphQL and how does it differ from REST?
Answer: GraphQL is a query language for APIs that allows clients to request exactly the data they need, nothing more. Unlike REST (multiple endpoints, over/under fetching), GraphQL uses a single endpoint and a strongly typed schema. It reduces payload size and number of round trips.
Explain the concept of “time to interactive” (TTI).
Answer: TTI measures the time from page load until the page is fully interactive (main thread idle, events can be handled). It includes loading resources, parsing, and script execution. Optimizing TTI involves code splitting, lazy loading, minimizing main thread work, and using web workers.
What is the purpose of the rel="noopener noreferrer" on hyperlinks?
Answer: When linking to an external site using target="_blank", the new page can access window.opener and potentially control the original page. rel="noopener" prevents this, improving security and performance. noreferrer additionally hides the referrer header.
How do you handle memory leaks in JavaScript?
Answer: Memory leaks occur when unreferenced objects are not garbage collected. Common causes: global variables, forgotten timers/intervals, detached DOM nodes, closures holding large data, event listeners not removed. Prevent by: clearing timers, removing event listeners before component unmount, and avoiding unnecessary global state.
What is the difference between --save and --save-dev in npm?
Answer: --save adds dependency to dependencies (runtime, production). --save-dev adds to devDependencies (build, testing, tooling – not needed in production). This helps keep production bundles slim.
What is a build tool (e.g., Vite, Webpack) and why is it used?
Answer: Build tools transform, bundle, and optimize code for production. They handle transpilation (TypeScript to JS, Sass to CSS), minification, tree shaking, code splitting, and hot module replacement during development. Vite is faster for development due to native ES modules.
How do you optimize images for the web?
Answer: Choose correct format (WebP/AVIF over JPEG/PNG). Use compression tools (ImageOptim, Squoosh). Serve responsive images with srcset. Use lazy loading (loading="lazy"). Implement a CDN with image transformation services. Use vector formats (SVG) for logos and icons.
What are CSS logical properties?
Answer: Logical properties (e.g., margin-inline-start, padding-block-end) are flow‑relative, adapting to writing modes (LTR, RTL, vertical). They replace physical properties (margin-left) for better internationalization and layout robustness.
What is the role of a linter (e.g., ESLint) in front‑end development?
Answer: ESLint statically analyzes code to find problematic patterns, syntax errors, and enforce coding style rules. It improves code quality, consistency, and catches bugs early. Can be integrated with editors and CI pipelines.
What is the difference between an inline element and a block element? Provide examples.
Answer: Inline elements do not start new lines and only occupy necessary width (<span>, <a>, <strong>, <img>). Block elements occupy full width, start new lines (<div>, <p>, <h1>, <section>). Inline‑block elements are inline but accept width/height.
What is the :root pseudo‑class in CSS?
Answer: :root matches the root element of the document (html) but has higher specificity than html. It is commonly used to define CSS custom properties (variables) that are globally available. It also helps with theming.
Explain the concept of “fouc” (flash of unstyled content) and how to prevent it.
Answer: FOUC occurs when a page renders unstyled HTML before CSS loads. Prevention: place CSS in the <head> (blocking render), use inline critical CSS, or use server‑side rendering. Also avoid using JavaScript to add styles after page load.
What are the advantages of using CSS Grid over older layout methods?
Answer: CSS Grid allows simultaneous row and column alignment, creating complex layouts with simple syntax, overlapping items, and responsive reordering without extra markup. It replaces float, table, and positioning hacks with clean, intuitive code.
What is the object-fit property?
Answer: object-fit specifies how an <img> or <video> should be resized to fit its container. Values: fill (stretch), contain (scale to fit within, letterbox), cover (cover entire container, may crop), scale-down, none. Essential for responsive media.
How do you make a website keyboard‑accessible?
Answer: Use semantic HTML (buttons, links, inputs are focusable). Manage focus order with tabindex appropriately, avoid tabindex > 0. Ensure focus indicators are visible (:focus styles). Use skip‑to‑content links. Trap focus inside modals. Test with only keyboard navigation.
What is the difference between a shallow render and a deep render in testing?
Answer: Shallow rendering (e.g., Enzyme’s shallow) renders a component without its child components, isolating the unit under test. Deep render (mount) renders the full component tree, which is more realistic but slower and more complex. React Testing Library encourages deep rendering.
Explain the concept of code splitting and dynamic imports.
Answer: Code splitting splits code into smaller bundles that can be loaded on demand or in parallel. Dynamic imports (import('./module.js')) return a promise, allowing lazy loading of components (e.g., with React.lazy and Suspense). This reduces initial bundle size and improves performance.
What is the purpose of the picture element?
Answer: The <picture> element allows serving different image sources based on media queries (resolution, viewport size, orientation). It can also specify image formats (e.g., WebP for modern browsers, fallback to JPEG). Helps implement art direction and responsive images.
What does will-change property do in CSS?
Answer: will-change hints to the browser which properties of an element are likely to change, so the browser can optimize ahead (e.g., create a separate compositor layer). Use sparingly on elements that actually animate, to avoid memory overhead.
What is the difference between clip-path and mask in CSS?
Answer: Both create visual clipping. clip-path defines a visible region using shapes (circle, polygon) – content outside is not interactive. mask uses an image or gradient to control transparency – more complex and allows soft edges. mask is newer and broader.
What are custom elements in Web Components?
Answer: Custom elements allow developers to define new HTML tags (e.g., <my-button>) with custom behavior, lifecycle callbacks (connectedCallback, disconnectedCallback), and attributes. They are reusable across frameworks without writing extra wrapper code.
How do you test front‑end code?
Answer: Unit tests (Jest, Vitest) for functions and components in isolation. Integration tests (React Testing Library) for component interaction. End‑to‑end tests (Cypress, Playwright) for user flows across browsers. Snapshot testing (Jest) for UI regression. Follow testing trophy: static types first, then unit/integration, fewer e2e.
What is the difference between HTTP/1.1, HTTP/2, and HTTP/3?
Answer: HTTP/1.1 uses sequential requests per connection, causing head‑of‑line blocking. HTTP/2 introduces multiplexing (multiple requests simultaneously), server push, and header compression. HTTP/3 replaces TCP with QUIC (UDP), reducing connection latency and improving performance on lossy networks.
What is a blob in JavaScript?
Answer: A Blob (Binary Large Object) represents raw binary data. It can be used to handle file downloads, create object URLs for images, or upload data. Example: new Blob(["Hello"], {type: "text/plain"}). You can create an object URL with URL.createObjectURL(blob).
What is the purpose of the preconnect and prefetch resource hints?
Answer: <link rel="preconnect" href="https://api.example.com"> tells the browser to set up early connection (DNS, TCP, TLS) to an origin, reducing latency. <link rel="prefetch" href="style.css" as="style"> downloads low‑priority resources for future navigation, caching them.
Explain the box‑model properties that affect layout shifts (CLS).
Answer: To avoid cumulative layout shift (CLS), set explicit dimensions (width/height or aspect‑ratio) on media elements. Use reserve‑space techniques for dynamically injected ads. Avoid inserting content above existing content. transform scale animations do not cause CLS.
What is the aspect-ratio CSS property?
Answer: aspect-ratio sets a preferred aspect ratio for an element (width/height). Example: aspect-ratio: 16 / 9. It helps prevent layout shifts by reserving space before media loads. Works without explicit dimensions.
What is a debounced search input? How would you implement it?
Answer: A debounced search input waits for the user to stop typing (e.g., 300ms) before making an API call, reducing unnecessary requests. Implementation: use setTimeout and clear it on each keystroke. Example:let timer; input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(fetchResults, 300); });
Modern libraries (Lodash) provide debounce.
What are the browser rendering stages (critical rendering path)?
Answer: 1) Parse HTML → DOM tree, parse CSS → CSSOM tree. 2) Combine DOM + CSSOM → Render tree. 3) Layout (reflow) – compute geometry. 4) Paint – fill pixels. 5) Composite – layers combined. JavaScript can block parsing and cause reflows.
How do you optimize third‑party scripts (e.g., analytics, chat widgets)?
Answer: Load them asynchronously (async or defer). Use link rel=”preconnect” for their origins. Lazy load non‑critical scripts (on user interaction). Use a tag manager with conditional loading. Self‑host when possible, or use facade (placeholder) until user interacts.
What is the resize observer?
Answer: ResizeObserver is a browser API that reports changes to an element’s size. Useful for responsive layouts, canvas resizing, or adjusting positioned elements when content changes. Unlike window resize event, it observes individual elements.
What is the Intersection Observer API used for?
Answer: Intersection Observer asynchronously watches for when an element enters or exits the viewport (or a parent element). Use for lazy loading images, infinite scroll, tracking ad visibility, or animating elements on scroll without performance penalties.
What is Server‑Sent Events (SSE) and how does it differ from WebSockets?
Answer: SSE allows the server to push events to the browser over a single HTTP connection (one‑way). WebSockets provide full‑duplex, bidirectional communication. SSE is simpler, uses standard HTTP, and is good for real‑time updates (notifications, feeds). WebSockets are for chat, games.
What is the difference between localStorage and sessionStorage lifetime?
Answer: localStorage data persists until explicitly cleared, across browser sessions. sessionStorage data is cleared when the page tab or browser is closed. Both are per‑origin.
Explain how flex property shorthand works (flex‑grow, flex‑shrink, flex‑basis).
Answer: flex: 1 means flex-grow: 1, flex-shrink: 1, flex-basis: 0%. flex: auto = 1 1 auto. flex: none = 0 0 auto. flex-grow distributes extra space, flex-shrink allows shrinking, flex-basis initial size. Shorthand is recommended.
What are the limitations of single‑page applications?
Answer: Larger initial JavaScript bundle, slower first paint (mitigated by SSR, code splitting). SEO challenges (though modern search engines can execute JS). More complex state management. Memory leaks if not careful. Accessibility can be harder if focus management ignored.
What is the history API in JavaScript?
Answer: The History API allows manipulation of the browser’s session history without page reloads. Methods: pushState(), replaceState(). It is the foundation for client‑side routing in SPAs, enabling URL changes without full page refresh.
How do you implement a modal dialog with accessibility in mind?
Answer: Use <dialog> element if supported, or custom <div> with role=”dialog”. Trap focus inside modal with tabindex and focus management. Add aria-modal=”true”, aria-label. Provide aria‑describedby. Close with Escape key. Restore focus to triggering element on close. Use inert attribute for background.
What is the Error boundary in React?
Answer: Error boundaries are React components that catch JavaScript errors in their child component tree, log them, and display a fallback UI. Implement componentDidCatch (class component) or use libraries (react‑error‑boundary). They do not catch errors in event handlers or async code.
What is the difference between rem and em?
Answer: (Earlier question repeated – but concise) rem relative to root html font‑size; em relative to parent element’s font‑size. Use rem for global consistency, em for component‑relative scaling.
How would you handle a large list of data in a table efficiently?
Answer: Use virtual scrolling (react‑window, react‑virtualized) to render only visible rows. Implement pagination or infinite scroll. Use keyed list for efficient re‑renders. Avoid inline functions in render. Memoize heavy computations. Web Workers for sorting/filtering large datasets.
What are the essential tools in your front‑end development workflow?
Answer: VS Code (with ESLint, Prettier), Git, npm/yarn/pnpm, Webpack/Vite, React/Vue, Chrome DevTools, Postman, Figma, Jest/Vitest, Cypress/Playwright, GitHub Actions/GitLab CI. I adapt based on project needs.
Why should we hire you as a front‑end developer?
Answer: I combine strong fundamentals (HTML, CSS, JS) with modern framework expertise and performance optimization. I care about user experience, accessibility, and maintainable code. I’m collaborative, a problem‑solver, and constantly learning. I build products that are fast, responsive, and accessible to everyone.