← Back to Interview Questions

Interview Preparation

💼 Frontend Interview

Master HTML, CSS, JavaScript, and modern framework concepts asked by top companies.

Loading questions... ⭐ View Bookmarked Questions
Question 1 of 40

No questions match your search. Try a different keyword.

All Frontend Interview Questions (47 total)

Below is the complete set of frontend interview questions used in the interactive practice tool above, covering HTML, CSS, JavaScript, the DOM, and core UI concepts. Click any question to reveal the full answer.

1. What is HTML? (Easy)

HTML (HyperText Markup Language) is the standard markup language used to define the structure and content of web pages. It uses a system of tags and elements to describe headings, paragraphs, links, images, forms, and other content that browsers render visually.

2. What is semantic HTML and why does it matter? (Easy)

Semantic HTML uses elements whose tag names describe their meaning, such as <header>, <nav>, <article>, <section>, and <footer>, instead of generic <div> elements. It improves accessibility for screen readers, helps search engines understand page structure for SEO, and makes code easier to read and maintain.

3. What is the difference between HTML elements and HTML attributes? (Easy)

An element is a complete unit made up of a start tag, content, and an end tag, such as <p>Hello</p>. An attribute provides additional information about an element and is written inside the opening tag, such as the 'src' attribute in <img src='photo.jpg'>. Attributes never appear alone; they always belong to an element.

4. What is the difference between <div> and <span>? (Easy)

<div> is a block-level element that starts on a new line and takes up the full available width, commonly used to group larger sections of content. <span> is an inline element that only takes up as much width as its content and is used to style or group small portions of text within a line.

5. What are data attributes in HTML and when would you use them? (Medium)

Data attributes are custom attributes prefixed with 'data-', such as data-user-id='42', that let you store extra information on an HTML element without affecting its appearance. They are commonly accessed through the dataset property in JavaScript to pass information between HTML and scripts without relying on classes or IDs.

6. What is the purpose of the alt attribute on an <img> tag? (Easy)

The alt attribute provides alternative text that describes an image's content or function. It is read aloud by screen readers for accessibility, displayed if the image fails to load, and used by search engines to understand image content, making it important for both accessibility and SEO.

7. What is the difference between <script>, <script async>, and <script defer>? (Medium)

A plain <script> tag blocks HTML parsing while it downloads and executes. 'async' downloads the script in parallel with parsing and executes it as soon as it's ready, potentially out of order. 'defer' also downloads in parallel but waits until HTML parsing is complete before executing, and preserves the order of multiple scripts.

8. What is the CSS box model? (Easy)

The CSS box model describes how every element is rendered as a rectangular box made up of four layers, from innermost to outermost: content, padding, border, and margin. Understanding this layering is essential for correctly calculating an element's total rendered size and spacing.

9. What is the difference between box-sizing: content-box and box-sizing: border-box? (Medium)

With content-box, the default, width and height apply only to the content area, so padding and border are added on top, increasing the total size. With border-box, width and height include the content, padding, and border, making it easier to predict an element's final rendered size.

10. What is the difference between Flexbox and CSS Grid? (Medium)

Flexbox is a one-dimensional layout system designed for arranging items in a single row or column, making it ideal for navigation bars or aligning items within a container. CSS Grid is a two-dimensional system that lets you control both rows and columns simultaneously, making it better suited for full page layouts.

11. What is the difference between position: relative, absolute, fixed, and sticky? (Medium)

'relative' positions an element relative to its normal position without removing it from the document flow. 'absolute' removes it from the flow and positions it relative to its nearest positioned ancestor. 'fixed' positions it relative to the viewport so it stays in place while scrolling. 'sticky' behaves like relative until a scroll threshold is reached, then acts like fixed.

12. What is CSS specificity and how is it calculated? (Medium)

Specificity determines which CSS rule applies when multiple rules target the same element. It is calculated as a weighted score based on the number of ID selectors, class/attribute/pseudo-class selectors, and element/pseudo-element selectors used, with IDs carrying more weight than classes, and classes carrying more weight than element selectors. Inline styles and !important override normal specificity rules.

13. What are CSS media queries used for? (Easy)

Media queries let you apply CSS rules conditionally based on characteristics of the device or viewport, such as width, height, or orientation. They are the foundation of responsive design, allowing a single stylesheet to adapt a layout for mobile phones, tablets, and desktop screens.

14. What is the difference between em, rem, %, and px units in CSS? (Medium)

px is an absolute unit representing a fixed pixel size. em is relative to the font size of the parent element, so it can compound in nested elements. rem is relative to the root (html) element's font size, avoiding compounding issues. Percentage units are relative to a property of the parent element, such as width or font size.

15. What is the difference between var, let, and const in JavaScript? (Easy)

'var' is function-scoped and can be redeclared and reassigned, and it is hoisted with an initial value of undefined. 'let' is block-scoped, can be reassigned but not redeclared in the same scope, and is not initialized when hoisted. 'const' is also block-scoped but cannot be reassigned after its initial declaration, though objects and arrays it references can still be mutated.

16. What is the difference between == and === in JavaScript? (Easy)

== performs loose equality comparison and converts operands to the same type before comparing, which can lead to unexpected results like '1' == 1 being true. === performs strict equality comparison without type conversion, so it only returns true when both the value and the type match, which is why it is generally the safer choice.

17. What is a closure in JavaScript? (Medium)

A closure is a function that retains access to variables from its outer (enclosing) scope even after that outer function has finished executing. Closures are commonly used to create private variables, implement data encapsulation, and build factory functions or memoized functions.

18. What is the difference between synchronous and asynchronous code in JavaScript? (Medium)

Synchronous code executes line by line, blocking further execution until the current operation completes. Asynchronous code allows long-running operations, such as network requests or timers, to run in the background without blocking the main thread, using mechanisms like callbacks, promises, or async/await to handle the result once it's ready.

19. What is a Promise in JavaScript? (Medium)

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It can be in one of three states: pending, fulfilled, or rejected, and it exposes .then(), .catch(), and .finally() methods to handle the outcome, making asynchronous code easier to read than nested callbacks.

20. What is the difference between async/await and Promises? (Medium)

async/await is syntactic sugar built on top of Promises that lets asynchronous code be written in a more synchronous, readable style. An async function always returns a Promise, and the await keyword pauses execution within that function until the awaited Promise settles, avoiding chained .then() calls while still relying on the same underlying Promise mechanism.

21. What is event bubbling and event capturing? (Medium)

Event bubbling is the phase where an event triggered on a nested element propagates upward through its ancestors in the DOM tree. Event capturing is the opposite phase, where the event travels from the root down to the target element before bubbling begins. Most event listeners use the bubbling phase by default unless capturing is explicitly enabled.

22. What is the 'this' keyword in JavaScript and how does its value get determined? (Medium)

'this' refers to the context in which a function is executed, and its value depends on how the function is called rather than where it is defined. In a regular function call it refers to the global object (or undefined in strict mode), in a method call it refers to the object the method belongs to, and in an arrow function it inherits 'this' from its surrounding lexical scope.

23. What is the difference between null and undefined? (Easy)

undefined means a variable has been declared but has not yet been assigned a value, and it is JavaScript's own default value. null is an explicit assignment representing the intentional absence of any object value, typically set by a developer to indicate 'no value'.

24. What is hoisting in JavaScript? (Medium)

Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their containing scope during the compile phase, before code execution. Function declarations are fully hoisted with their definitions, var declarations are hoisted but initialized as undefined, while let and const are hoisted but remain in a 'temporal dead zone' until their declaration line executes.

25. What is the difference between map(), filter(), and reduce() in JavaScript arrays? (Medium)

map() transforms each element of an array and returns a new array of the same length. filter() returns a new array containing only the elements that pass a test condition, potentially shorter than the original. reduce() iterates through the array to accumulate a single value, such as a sum or object, based on a reducer function.

26. What is React and what problem does it solve? (Easy)

React is a JavaScript library for building user interfaces using a component-based architecture. It solves the problem of efficiently updating the DOM by using a virtual DOM to calculate the minimal set of changes needed, and it encourages building UIs as reusable, composable components that manage their own state.

27. What is the virtual DOM in React? (Medium)

The virtual DOM is a lightweight, in-memory representation of the real DOM. When a component's state changes, React creates a new virtual DOM tree, compares it with the previous one using a diffing algorithm, and updates only the parts of the real DOM that actually changed, improving rendering performance.

28. What is the difference between props and state in React? (Easy)

Props are read-only values passed into a component from its parent, used to configure or customize how it renders. State is data managed internally within a component that can change over time, usually in response to user interaction, and updating it triggers a re-render.

29. What is the difference between a class component and a functional component in React? (Medium)

Class components are ES6 classes that extend React.Component and manage state using this.state and lifecycle methods like componentDidMount. Functional components are plain JavaScript functions that use React Hooks, such as useState and useEffect, to manage state and side effects, and they are now the preferred approach in modern React development.

30. What is the useEffect hook used for in React? (Medium)

useEffect lets a functional component perform side effects, such as fetching data, subscribing to events, or manually updating the DOM, after rendering. It accepts a dependency array that controls when the effect re-runs, and can optionally return a cleanup function that runs before the component unmounts or before the effect runs again.

31. Why does React require a unique 'key' prop when rendering lists? (Medium)

Keys give React a stable identity for each item in a list, allowing it to efficiently determine which items were added, removed, or reordered during re-renders. Without proper keys, React may re-render or reorder list items incorrectly, causing bugs with component state or unnecessary DOM updates.

32. What is responsive web design? (Easy)

Responsive web design is an approach to building websites that automatically adapt their layout, images, and content to look and function well across different screen sizes and devices, typically using fluid grids, flexible images, and CSS media queries.

33. What is a mobile-first design approach? (Medium)

Mobile-first design means writing base CSS styles for small screens first, then progressively enhancing the layout for larger screens using min-width media queries. This approach tends to produce leaner, faster-loading pages since mobile users only download the styles relevant to their screen size instead of overriding desktop styles.

34. What is the viewport meta tag and why is it important? (Easy)

The viewport meta tag, written as <meta name='viewport' content='width=device-width, initial-scale=1.0'>, tells mobile browsers to set the page width to match the device's screen width and to use a default zoom level of 1. Without it, mobile browsers render pages at a desktop width and scale them down, making text and elements too small to read.

35. What are relative and fluid layout units, and why are they preferred in responsive design? (Medium)

Relative units like percentages, em, rem, vw, and vh scale based on their parent container, the root font size, or the viewport size, rather than being fixed like pixels. They are preferred in responsive design because they allow layouts, text, and spacing to adapt naturally to different screen sizes without requiring separate fixed-size rules for every breakpoint.

36. What is localStorage and how is it different from sessionStorage? (Easy)

Both are browser Web Storage APIs that store key-value string data on the client side. localStorage persists data indefinitely, even after the browser is closed and reopened, until it is explicitly cleared. sessionStorage only persists data for the duration of the page session and is cleared once the browser tab is closed.

37. What is the Fetch API used for? (Easy)

The Fetch API is a modern browser interface for making HTTP requests to servers, replacing the older XMLHttpRequest. It returns a Promise that resolves to a Response object, and is commonly used with async/await to retrieve or send JSON data, handle status codes, and manage network errors.

38. What is the difference between cookies, localStorage, and sessionStorage? (Medium)

Cookies are small pieces of data (up to about 4KB) that are automatically sent to the server with every HTTP request and can have an expiration date. localStorage and sessionStorage store larger amounts of data (up to about 5-10MB) entirely on the client side and are never sent to the server automatically, with the difference between them being persistence duration.

39. What is the Geolocation API? (Easy)

The Geolocation API is a browser API that allows web applications to request the user's current geographic location, typically via navigator.geolocation.getCurrentPosition(). It requires explicit user permission for privacy reasons and returns coordinates such as latitude and longitude that can be used for location-based features.

40. What is the DOM (Document Object Model)? (Easy)

The DOM is a tree-like, programmatic representation of an HTML document that browsers create when they load a page. It represents each HTML element as a node object, allowing JavaScript to read, add, remove, or modify page content, structure, and styling dynamically.

41. What is the difference between document.getElementById, querySelector, and querySelectorAll? (Easy)

getElementById selects a single element by its exact ID and is the fastest lookup method. querySelector returns the first element matching any valid CSS selector. querySelectorAll returns a static NodeList of all elements matching a CSS selector, which can be iterated but does not automatically update when the DOM changes.

42. What is DOM manipulation and why can excessive manipulation hurt performance? (Medium)

DOM manipulation refers to using JavaScript to add, remove, or change elements and attributes in the live document tree. Frequent, unbatched manipulations can hurt performance because each change may trigger the browser to recalculate layout and repaint the page (reflow), so developers often batch updates or use techniques like document fragments to minimize reflows.

43. What is the difference between innerHTML and textContent? (Medium)

innerHTML gets or sets the HTML markup inside an element, meaning any string assigned to it is parsed as HTML, which can introduce cross-site scripting (XSS) risks with untrusted input. textContent gets or sets only the plain text content of an element, treating any string as literal text rather than parsing it as markup, making it the safer choice for inserting user-supplied content.

44. How do you attach an event listener to an element in JavaScript? (Easy)

You use the addEventListener method, for example element.addEventListener('click', handlerFunction). This is preferred over inline HTML event attributes or the onclick property because it allows multiple listeners on the same event and gives finer control over the capturing and bubbling phases.

45. What does event.preventDefault() do? (Medium)

preventDefault() stops the browser's default action associated with an event from occurring, such as preventing a form from submitting, a link from navigating, or a checkbox from toggling, while still allowing the event to continue propagating through the DOM unless stopPropagation() is also called.

46. What is event delegation and why is it useful? (Medium)

Event delegation is a pattern where a single event listener is attached to a common parent element instead of attaching listeners to many individual child elements. It relies on event bubbling, and is useful because it reduces memory usage and automatically handles events for dynamically added child elements without needing to reattach listeners.

47. What is the difference between event.target and event.currentTarget? (Medium)

event.target refers to the actual DOM element that originally triggered the event, which can be a descendant of the element the listener is attached to. event.currentTarget refers to the element the event listener is currently attached to and actively handling the event on, which stays constant during that handler's execution.