React Interview Questions

Filter by Category

Question

What is React and what are its main features?

Answer

React is a JavaScript library for building user interfaces. Its main features include: Virtual DOM, Component-based architecture, Unidirectional data flow, JSX syntax, and React Native for mobile development.

Question

What is the Virtual DOM and how does it work?

Answer

The Virtual DOM is a programming concept where a virtual representation of the UI is kept in memory and synced with the 'real' DOM. When state changes, React creates a new virtual DOM tree, compares it with the previous one, and efficiently updates only the changed parts in the real DOM.

Question

What are React Hooks and why were they introduced?

Answer

React Hooks are functions that allow you to use state and other React features in functional components. They were introduced to solve problems with class components like: complex logic reuse, wrapper hell, and confusing class syntax.

Question

What is the difference between state and props?

Answer

Props are read-only data passed from parent to child components, while state is mutable data managed within a component. Props flow down, while state can be updated within the component using setState or useState.

Question

What is the purpose of useEffect hook?

Answer

useEffect is used for handling side effects in functional components. It runs after every render and can be used for: data fetching, subscriptions, or manually changing the DOM. It can also be configured to run only when specific dependencies change.

Question

What is JSX and how does it work?

Answer

JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files. It gets transformed into regular JavaScript function calls during compilation, making it easier to write and understand React components.

Question

What is the difference between controlled and uncontrolled components?

Answer

Controlled components are React components that render a form element whose value is controlled by React state. Uncontrolled components are form elements where the form data is handled by the DOM itself. Controlled components provide better control over form data and validation.

Question

What is React Context and when should you use it?

Answer

React Context provides a way to pass data through the component tree without having to pass props manually at every level. It's useful for sharing global data like themes, user authentication, or language preferences.

Question

What is the purpose of useMemo and useCallback?

Answer

useMemo and useCallback are performance optimization hooks. useMemo memoizes computed values, while useCallback memoizes functions. They prevent unnecessary re-renders and computations in child components.

Question

What is the difference between React.memo and useMemo?

Answer

React.memo is a higher-order component that prevents re-renders of a component if its props haven't changed. useMemo is a hook that memoizes computed values. React.memo is for component memoization, while useMemo is for value memoization.

Question

What is the primary way to manage state in a functional React component?

Answer

The useState hook is the primary way to manage state in functional components.

Question

How does useReducer differ from useState?

Answer

useReducer is better for complex state logic with multiple values or transitions, while useState is simpler for independent state variables.

Question

What is the purpose of the Context API?

Answer

The Context API allows you to share state across the component tree without prop drilling.

Question

When should you use Redux instead of Context?

Answer

Redux is preferred for large-scale apps with complex state management, debugging needs, or middleware requirements.

Question

What does the useState hook return?

Answer

It returns an array with the current state value and a function to update it.

Question

What is prop drilling?

Answer

Prop drilling is passing props through multiple layers of components to reach a deeply nested one.

Question

How can you avoid prop drilling?

Answer

Use the Context API or a state management library like Redux to avoid prop drilling.

Question

What's a reducer in Redux?

Answer

A pure function that takes the current state and an action to return a new state.

Question

What are actions in Redux?

Answer

Actions are payloads of information that send data from your app to the Redux store.

Question

What is the role of the dispatch function in Redux?

Answer

Dispatch sends an action to the reducer to update the state.

Question

What is lifting state up in React?

Answer

Lifting state up means moving state to a common parent component to share it between siblings.

Question

How do you optimize state updates to avoid re-renders?

Answer

Use useMemo, useCallback, or split state into smaller pieces to prevent unnecessary updates.

Question

What is the useContext hook?

Answer

useContext lets you consume a context value in a functional component.

Question

What's a common use case for Context API?

Answer

Sharing themes, user authentication, or global settings across components.

Question

What is Zustand?

Answer

Zustand is a lightweight state management library for React with a simple API.

Question

How does MobX differ from Redux?

Answer

MobX uses observable state and reactive updates, while Redux relies on immutable state and reducers.

Question

What is a store in Redux?

Answer

The store is a single source of truth that holds the entire state of the app.

Question

What's the benefit of immutable state?

Answer

Immutable state ensures predictability and easier debugging by preventing direct mutations.

Question

How do you handle async actions in Redux?

Answer

Use middleware like Redux Thunk or Redux Saga to handle asynchronous logic.

Question

What's the role of selectors in state management?

Answer

Selectors are functions that extract specific pieces of state for reuse and optimization.

Question

What is the Provider component in React?

Answer

Provider is a component from Context or Redux that makes state available to child components.

Question

How do you combine multiple reducers in Redux?

Answer

Use combineReducers to merge multiple reducers into a single root reducer.

Question

What's a common pitfall with useState?

Answer

Not understanding that state updates are asynchronous, leading to stale values.

Question

How do you update an object in useState?

Answer

Spread the previous state and override specific properties to ensure immutability.

Question

What's the difference between local and global state?

Answer

Local state is managed within a component; global state is shared across the app.

Question

What is Redux Toolkit?

Answer

Redux Toolkit is an official package that simplifies Redux setup with utilities like createSlice.

Question

How does useState handle function updates?

Answer

Pass a function to the updater to safely compute the next state based on the previous one.

Question

What's a side effect of overusing Context?

Answer

Overusing Context can lead to unnecessary re-renders of all consumers.

Question

What is memoization in state management?

Answer

Memoization caches computed values to avoid recalculating them on every render.

Question

How do you debug state changes in React?

Answer

Use React DevTools or console.log within useEffect to track state changes.

Question

What are React Hooks?

Answer

Hooks are functions that let you use state and other React features in functional components.

Question

Explain the concept of hooks in React? Give examples of useState and useEffect hooks?

Answer

Hooks let you use state and lifecycle features in functional components. useState manages state (e.g., const [count, setCount] = useState(0)), while useEffect handles side effects (e.g., useEffect(() => { fetchData(); }, [])).

Question

What is the purpose of useEffect?

Answer

useEffect handles side effects like data fetching, subscriptions, or DOM manipulation after render.

Question

How do you cleanup in useEffect?

Answer

Return a cleanup function from useEffect, which runs before the next effect or on unmount.

Question

What does useMemo do?

Answer

useMemo memoizes expensive computations so they only rerun when dependencies change.

Question

Can you call Hooks conditionally?

Answer

No, Hooks must be called at the top level of a component, not inside loops, conditions, or nested functions.

Question

What is useCallback used for?

Answer

useCallback memoizes a function so it doesn't recreate on every render, useful for passing to child components.

Question

What's the difference between useEffect and useLayoutEffect?

Answer

useEffect runs after paint; useLayoutEffect runs synchronously after DOM updates but before paint.

Question

What is useRef?

Answer

useRef creates a mutable reference that persists across renders, often used for DOM access.

Question

How do you access a DOM element with useRef?

Answer

Pass the ref to the ref attribute of an element, then access it via ref.current.

Question

What happens if you forget a dependency in useEffect?

Answer

The effect might use stale values or not run when it should, causing bugs.

Question

What's a custom hook?

Answer

A custom hook is a reusable function that encapsulates logic using built-in hooks.

Question

How do you share logic between components with hooks?

Answer

Create a custom hook to extract and reuse stateful logic.

Question

What's the purpose of useReducer?

Answer

useReducer manages complex state logic, similar to Redux, with a reducer function.

Question

What does useState's lazy initialization mean?

Answer

Pass a function to useState to compute the initial value only once, not on every render.

Question

How do you trigger useEffect only on mount?

Answer

Use an empty dependency array ([]) to run useEffect only once on mount.

Question

What's the role of dependencies in useMemo?

Answer

Dependencies tell useMemo when to recompute the memoized value.

Question

Can useEffect run before render?

Answer

No, useEffect always runs after render; useLayoutEffect can run before paint.

Question

What's an example of a side effect?

Answer

Fetching data, setting up a subscription, or updating the document title.

Question

How do you conditionally run useEffect?

Answer

Add conditions inside useEffect or adjust the dependency array.

Question

What's useImperativeHandle?

Answer

It customizes the instance value exposed when using ref with forwardRef.

Question

How does useContext work with hooks?

Answer

useContext consumes a context value created by createContext.

Question

What's the benefit of memoizing with useCallback?

Answer

It prevents child components from re-rendering due to new function instances.

Question

How do you handle errors in useEffect?

Answer

Use try/catch inside an async function called within useEffect.

Question

What's a common mistake with useState?

Answer

Assuming state updates immediately instead of on the next render.

Question

How do you debug a hook?

Answer

Use console.log in the hook or React DevTools to inspect state and effects.

Question

What's the difference between useMemo and useCallback?

Answer

useMemo memoizes a value; useCallback memoizes a function.

Question

Can hooks be used in class components?

Answer

No, hooks are designed for functional components only.

Question

What's the purpose of useDebugValue?

Answer

It displays a label for custom hooks in React DevTools.

Question

How do you handle multiple useEffects?

Answer

Split them by concern or combine related logic into one useEffect.

Question

What replaces componentDidMount in functional components?

Answer

useEffect with an empty dependency array mimics componentDidMount.

Question

When does useEffect run by default?

Answer

useEffect runs after every render unless you specify dependencies.

Question

What was the purpose of componentWillUnmount?

Answer

It was used to clean up resources (e.g., timers) before a component unmounts.

Question

How do you handle updates in a functional component?

Answer

Use useEffect with specific dependencies to run code when those values change.

Question

What triggers a re-render in React?

Answer

A re-render occurs when state or props change, or the parent component re-renders.

Question

What is the mounting phase?

Answer

Mounting is when a component is created and inserted into the DOM.

Question

What happens in the updating phase?

Answer

React updates the DOM when state or props change during the updating phase.

Question

What's the unmounting phase?

Answer

Unmounting is when a component is removed from the DOM.

Question

What was componentDidUpdate used for?

Answer

It ran after a component updated due to state or prop changes.

Question

How do you mimic componentWillUnmount with hooks?

Answer

Return a cleanup function from useEffect to run on unmount.

Question

What's the difference between mounting and rendering?

Answer

Mounting is the initial DOM insertion; rendering is generating the UI (can happen multiple times).

Question

How does React handle initial render?

Answer

React creates the virtual DOM, reconciles it, and commits it to the real DOM.

Question

What's a side effect in the lifecycle?

Answer

A side effect is an operation like fetching data that happens after render.

Question

How do you prevent unnecessary re-renders?

Answer

Use memoization (React.memo, useMemo) or optimize state updates.

Question

What was componentWillMount used for?

Answer

It ran before mounting, but it's deprecated due to misuse and side effects.

Question

How does useLayoutEffect fit into the lifecycle?

Answer

It runs synchronously after DOM updates but before the browser paints.

Question

What's the commit phase?

Answer

The commit phase is when React applies changes to the real DOM after reconciliation.

Question

How do you log every render?

Answer

Use useEffect with no dependencies to log after every render.

Question

What's the role of keys in the lifecycle?

Answer

Keys help React track elements across renders to optimize updates.

Question

What happens if a parent re-renders?

Answer

Child components re-render unless memoized with React.memo.

Question

What's the difference between render and commit?

Answer

Render generates the virtual DOM; commit applies it to the real DOM.

Question

How do you handle errors in the lifecycle?

Answer

Use error boundaries with componentDidCatch or static getDerivedStateFromError.

Question

What's getDerivedStateFromProps?

Answer

A static lifecycle method that updates state based on prop changes.

Question

Why was componentWillReceiveProps deprecated?

Answer

It caused confusion and bugs; use getDerivedStateFromProps instead.

Question

How do you simulate componentDidMount with hooks?

Answer

Use useEffect with an empty array to run once on mount.

Question

What's the paint phase?

Answer

The browser renders the updated DOM to the screen after React commits changes.

Question

How does React batch state updates?

Answer

React batches multiple setState calls in event handlers for performance.

Question

What's the role of shouldComponentUpdate?

Answer

It determines if a class component should re-render; not needed in hooks.

Question

How do you handle async lifecycle events?

Answer

Use useEffect with async/await inside a separate function.

Question

What's the lifecycle of a functional component?

Answer

Mount (render + useEffect), update (re-render + useEffect), unmount (cleanup).

Question

What is JSX?

Answer

JSX is a syntax extension for JavaScript that looks like HTML and is used to define React elements.

Question

How do you add a comment in JSX?

Answer

Use {/* comment */} inside JSX, as regular HTML comments don't work.

Question

What does the 'key' prop do in a list?

Answer

The 'key' prop helps React identify which items in a list have changed, added, or removed.

Question

Can you use if statements directly in JSX?

Answer

No, you must use ternary operators or move logic outside the return statement.

Question

How do you bind an event in JSX?

Answer

Pass a function to an event handler like onClick={handleClick}, without invoking it.

Question

What's a fragment in JSX?

Answer

A fragment (<> </>) lets you group elements without adding extra DOM nodes.

Question

How do you render a list in JSX?

Answer

Use map to iterate over an array and return JSX elements with keys.

Question

What's the difference between HTML and JSX?

Answer

JSX uses camelCase attributes (e.g., onClick) and requires JavaScript expressions in {}.

Question

How do you apply inline styles in JSX?

Answer

Use an object with camelCase properties, like style={{ color: 'red' }}.

Question

What's a ternary operator used for in JSX?

Answer

It's used for conditional rendering, e.g., {isTrue ? <p>Yes</p> : <p>No</p>}.

Question

How do you pass props in JSX?

Answer

Pass props as attributes, like <Component name='John' />.

Question

What's the role of the children prop in JSX?

Answer

Children represent content passed between opening and closing tags of a component.

Question

How do you render dynamic content in JSX?

Answer

Use curly braces {} to embed JavaScript expressions, like {user.name}.

Question

What happens if you forget a key in a list?

Answer

React warns you, and it may struggle to efficiently update the list.

Question

How do you conditionally render multiple elements?

Answer

Use && or map with a condition, e.g., {items.length && <p>Items exist</p>}.

Question

What's the difference between JSX and a string?

Answer

JSX is compiled to React.createElement calls, not a string; it's a syntax sugar.

Question

How do you use a component in JSX?

Answer

Use it like a tag, e.g., <MyComponent />, with a capital letter.

Question

What's the purpose of dangerouslySetInnerHTML?

Answer

It lets you render raw HTML, but it's risky due to XSS vulnerabilities.

Question

How do you handle forms in JSX?

Answer

Use controlled components with state and onChange handlers.

Question

What's a common JSX gotcha?

Answer

Forgetting that attributes like className use camelCase, not class.

Question

How do you render nothing in JSX?

Answer

Return null or an empty fragment (</>).

Question

What's the role of babel in JSX?

Answer

Babel transpiles JSX into React.createElement calls for the browser.

Question

How do you spread props in JSX?

Answer

Use the spread operator, e.g., <Component {...props} />.

Question

What's a self-closing tag in JSX?

Answer

A tag like <img /> that doesn't need a closing tag or children.

Question

How do you type JSX with TypeScript?

Answer

Use interfaces for props, e.g., interface Props { name: string }.

Question

What's the difference between {} and {{}} in JSX?

Answer

{} embeds expressions; {{}} is for inline style objects.

Question

How do you render an array of components?

Answer

Map over the array and return JSX, ensuring each has a unique key.

Question

What's a common error with JSX?

Answer

Returning multiple root elements without a wrapper or fragment.

Question

How do you handle input values in JSX?

Answer

Use the value attribute and an onChange handler for controlled inputs.

Question

What's the benefit of JSX over vanilla JS?

Answer

JSX provides a declarative, HTML-like syntax for building UI.

Question

What is the virtual DOM?

Answer

The virtual DOM is a lightweight copy of the real DOM that React uses to optimize updates.

Question

How does the virtual DOM work in React, and why is it beneficial?

Answer

React creates a virtual DOM, diffs it with the previous version, and updates only changed parts of the real DOM. It's beneficial for performance by minimizing direct DOM manipulation.

Question

What are the main differences between functional and class components in React?

Answer

Functional components use hooks for state and lifecycle, are simpler, and lack this; class components use lifecycle methods and have a more verbose syntax.

Question

What is a React component?

Answer

A React component is a reusable piece of UI, typically a function or class that returns JSX.

Question

What's the difference between state and props?

Answer

State is internal and managed by the component; props are external inputs passed to it.

Question

What is React's reconciliation process?

Answer

Reconciliation is how React compares the virtual DOM with the real DOM to apply minimal updates.

Question

What is React Router?

Answer

React Router is a library for handling client-side routing in React apps.

Question

What's an error boundary?

Answer

An error boundary is a component that catches JavaScript errors in its child tree.

Question

What's React.memo?

Answer

React.memo prevents re-rendering of a component if its props haven't changed.

Question

What's a higher-order component (HOC)?

Answer

An HOC is a function that takes a component and returns an enhanced version.

Question

What's the purpose of React.StrictMode?

Answer

StrictMode highlights potential problems in development by enabling extra checks.

Question

What's concurrent rendering in React 18?

Answer

Concurrent rendering allows React to pause and resume renders for better performance.

Question

What's the role of keys in React?

Answer

Keys help React efficiently update lists by identifying unique elements.

Question

What's the difference between controlled and uncontrolled components?

Answer

Controlled components use state to manage form data; uncontrolled use refs.

Question

What's the benefit of one-way data flow?

Answer

One-way data flow makes data predictable and easier to debug.

Question

What's the purpose of useId in React 18?

Answer

useId generates unique IDs for accessibility in server-rendered apps.

Question

How do you optimize React performance?

Answer

Use memoization, lazy loading, and avoid unnecessary re-renders.

Question

What's the role of the React DevTools?

Answer

React DevTools lets you inspect component hierarchies and state.

Question

What's a render prop?

Answer

A render prop is a function prop that a component uses to render content.

Question

What's the difference between React and ReactDOM?

Answer

React is the core library; ReactDOM handles DOM-specific rendering.

Question

What's lazy loading in React?

Answer

Lazy loading defers loading of components until they're needed, using React.lazy.

Question

What's Suspense in React?

Answer

Suspense lets you wait for async content (e.g., lazy-loaded components) to load.

Question

How do you handle events in React?

Answer

Use synthetic events like onClick with handler functions.

Question

What's the purpose of forwardRef?

Answer

forwardRef passes a ref through a component to one of its children.

Question

What's a portal in React?

Answer

A portal renders children into a DOM node outside the parent hierarchy.

Question

What's the difference between client-side and server-side rendering?

Answer

Client-side renders in the browser; server-side pre-renders on the server.

Question

What's Next.js?

Answer

Next.js is a React framework for server-side rendering and static site generation.

Question

How do you test React components?

Answer

Use libraries like Jest and React Testing Library to test rendering and behavior.

Question

What's the role of createElement?

Answer

createElement builds React elements; JSX is compiled to it under the hood.

Question

Why is React declarative?

Answer

React lets you describe what the UI should look like, and it handles the how.

Question

What is the difference between let and var?

Answer

let is block-scoped and doesn't hoist to the top of the function, while var is function-scoped and hoists with an undefined value.

Question

What does const mean in JavaScript?

Answer

const declares a variable that cannot be reassigned, but its properties (e.g., in objects) can still be mutated.

Question

What is hoisting in JavaScript?

Answer

Hoisting moves variable and function declarations to the top of their scope during compilation, but not their assignments.

Question

What is a closure?

Answer

A closure is a function that retains access to its outer scope's variables even after the outer function has finished executing.

Question

What's the difference between == and ===?

Answer

== checks equality with type coercion; === checks strict equality without coercion.

Question

What is the purpose of the this keyword?

Answer

this refers to the context in which a function is executed, often the object it's called on.

Question

How does JavaScript handle asynchronous code?

Answer

JavaScript uses an event loop with callbacks, promises, or async/await to handle asynchronous operations.

Question

What is a promise?

Answer

A promise is an object representing the eventual completion or failure of an asynchronous operation.

Question

What does the async keyword do?

Answer

async makes a function return a promise and allows the use of await inside it.

Question

What is the purpose of await?

Answer

await pauses the execution of an async function until a promise resolves, returning its value.

Question

What's the difference between null and undefined?

Answer

null is an intentional absence of value; undefined means a variable has been declared but not assigned.

Question

What is an IIFE?

Answer

An Immediately Invoked Function Expression (IIFE) is a function that runs as soon as it's defined, often for scoping.

Question

What does the bind method do?

Answer

bind creates a new function with a fixed this value and optional preset arguments.

Question

What's the difference between call and apply?

Answer

call invokes a function with a given this and arguments individually; apply uses an array of arguments.

Question

What is event delegation?

Answer

Event delegation uses a parent element to handle events on its children, leveraging event bubbling.

Question

What is the event loop?

Answer

The event loop manages the execution of asynchronous tasks by processing the call stack and task queue.

Question

What does the spread operator (...) do?

Answer

The spread operator expands an iterable (like an array) into individual elements or copies object properties.

Question

What is the rest parameter?

Answer

The rest parameter (...args) collects remaining arguments into an array in a function.

Question

What's a higher-order function?

Answer

A higher-order function takes a function as an argument or returns a function.

Question

What is currying?

Answer

Currying transforms a function with multiple arguments into a sequence of single-argument functions.

Question

What's the difference between map and forEach?

Answer

map returns a new array with transformed elements; forEach executes a function without returning anything.

Question

What does filter do?

Answer

filter creates a new array with elements that pass a test provided by a callback function.

Question

What is reduce used for?

Answer

reduce applies a function to an accumulator and each element to reduce the array to a single value.

Question

What's a prototype in JavaScript?

Answer

A prototype is an object from which other objects inherit properties and methods.

Question

What is prototypal inheritance?

Answer

Prototypal inheritance allows objects to inherit properties and methods from a prototype object.

Question

What does Object.create do?

Answer

Object.create creates a new object with a specified prototype.

Question

What's the difference between deep and shallow copy?

Answer

A shallow copy duplicates top-level properties; a deep copy duplicates all nested levels.

Question

How do you create a deep copy of an object?

Answer

Use structuredClone, JSON.parse(JSON.stringify(obj)), or a recursive function.

Question

What is a generator function?

Answer

A generator function (function*) returns an iterator and can pause execution with yield.

Question

What's the purpose of yield?

Answer

yield pauses a generator function and returns a value to the caller.

Question

What is a Symbol?

Answer

Symbol is a primitive type for creating unique identifiers, often used as object keys.

Question

What does typeof return for an array?

Answer

typeof returns 'object' because arrays are objects in JavaScript.

Question

What is the global object in a browser?

Answer

The global object in a browser is window, which contains all global variables and functions.

Question

What's the difference between setTimeout and setInterval?

Answer

setTimeout runs once after a delay; setInterval runs repeatedly at an interval.

Question

How do you stop setInterval?

Answer

Use clearInterval with the interval ID returned by setInterval.

Question

What is a WeakMap?

Answer

A WeakMap is a collection of key-value pairs where keys are objects and are weakly referenced.

Question

What's the benefit of WeakMap over Map?

Answer

WeakMap allows garbage collection of keys, preventing memory leaks.

Question

What is a Proxy in JavaScript?

Answer

A Proxy wraps an object to intercept and customize operations like property access.

Question

What does Array.isArray do?

Answer

Array.isArray checks if a value is an array, returning true or false.

Question

What's the difference between splice and slice?

Answer

splice modifies the array by adding/removing elements; slice returns a new array without modifying.

Question

What is a callback function?

Answer

A callback is a function passed as an argument to be executed later.

Question

What's callback hell?

Answer

Callback hell is deeply nested callbacks that make code hard to read and maintain.

Question

How do promises solve callback hell?

Answer

Promises provide a cleaner way to chain asynchronous operations with .then and .catch.

Question

What's the difference between throw and return?

Answer

throw raises an error to be caught; return exits a function with a value.

Question

What is strict mode?

Answer

Strict mode ('use strict') enforces stricter parsing and error handling in JavaScript.

Question

What does Object.freeze do?

Answer

Object.freeze prevents modifications to an object's properties.

Question

What's the difference between for...in and for...of?

Answer

for...in loops over enumerable keys; for...of loops over iterable values.

Question

What is a module in JavaScript?

Answer

A module is a file that exports and imports functionality using export and import.

Question

What's the difference between CommonJS and ES6 modules?

Answer

CommonJS uses require and module.exports; ES6 uses import and export.

Question

What is the purpose of try/catch?

Answer

try/catch handles errors by running code in try and catching exceptions in catch.

Question

What is the difference between inline, internal, and external CSS?

Answer

Inline CSS is applied directly to HTML elements via the style attribute; internal CSS is defined in a <style> tag within the HTML head; external CSS is written in a separate .css file linked via <link>.

Question

How do CSS Flexbox and CSS Grid differ, and when would you use each?

Answer

Flexbox is one-dimensional (rows or columns) and ideal for aligning items or simple layouts; Grid is two-dimensional (rows and columns) and better for complex, grid-based layouts like dashboards.

Question

Explain the concept of specificity in CSS and how it affects the application of styles

Answer

Specificity determines which CSS rule applies when multiple rules target the same element. It's calculated by weights (inline > ID > class > element), with higher specificity overriding lower.

Question

What does the box model consist of?

Answer

The box model includes content, padding, border, and margin, defining an element's space and layout.

Question

What's the difference between margin and padding?

Answer

Margin is the space outside an element's border; padding is the space inside, between the border and content.

Question

What is the purpose of the display property?

Answer

The display property controls how an element is rendered, like block, inline, flex, or none.

Question

What does position: absolute do?

Answer

position: absolute removes an element from the normal flow and positions it relative to its nearest positioned ancestor.

Question

How does position: relative differ from position: absolute?

Answer

position: relative keeps the element in the flow and offsets it from its original position; absolute removes it from the flow.

Question

What is the z-index property?

Answer

z-index controls the stacking order of positioned elements, with higher values appearing on top.

Question

What's the difference between block and inline elements?

Answer

Block elements take full width and stack vertically; inline elements flow horizontally and only take needed width.

Question

What does float do in CSS?

Answer

float moves an element to the left or right, allowing content to wrap around it.

Question

How do you clear a float?

Answer

Use clear: both on an element or the clearfix hack (overflow: hidden on a parent).

Question

What is a pseudo-class?

Answer

A pseudo-class (e.g., :hover) targets an element's state, like when it's hovered or focused.

Question

What's a pseudo-element?

Answer

A pseudo-element (e.g., ::before) styles a specific part of an element, like adding content before it.

Question

What does the * selector do?

Answer

The universal selector (*) targets all elements on the page.

Question

What's the difference between em and rem units?

Answer

em is relative to the parent's font size; rem is relative to the root (html) font size.

Question

What is the vh unit?

Answer

vh is 1% of the viewport's height, useful for responsive layouts.

Question

What does overflow: hidden do?

Answer

overflow: hidden clips content that exceeds an element's bounds and hides it.

Question

What's the purpose of box-sizing: border-box?

Answer

box-sizing: border-box includes padding and border in an element's total width and height.

Question

How do you center an element horizontally?

Answer

Use margin: 0 auto on a block element with a set width.

Question

How do you vertically center an element with Flexbox?

Answer

Use display: flex and align-items: center on the parent.

Question

What is the purpose of justify-content in Flexbox?

Answer

justify-content aligns flex items along the main axis (e.g., space-between, center).

Question

What does align-items do in Flexbox?

Answer

align-items aligns flex items along the cross axis (e.g., center, stretch).

Question

What is the grid-template-columns property?

Answer

grid-template-columns defines the number and size of columns in a CSS Grid layout.

Question

What does grid-gap do?

Answer

grid-gap (or gap) sets the spacing between grid rows and columns.

Question

What's the difference between visibility: hidden and display: none?

Answer

visibility: hidden hides an element but keeps its space; display: none removes it entirely.

Question

What is the purpose of the opacity property?

Answer

opacity sets the transparency of an element, from 0 (invisible) to 1 (opaque).

Question

What does transform: translate do?

Answer

transform: translate moves an element along the X and/or Y axis without affecting layout.

Question

What is a CSS transition?

Answer

A transition smoothly animates property changes over time (e.g., transition: color 0.3s).

Question

What's the difference between transition and animation?

Answer

Transitions animate between two states; animations define keyframes for complex sequences.

Question

What does @keyframes do?

Answer

@keyframes defines the stages of an animation, specifying styles at different points.

Question

What is the purpose of the media query?

Answer

Media queries apply styles based on conditions like screen size (e.g., @media (max-width: 600px)).

Question

What's the mobile-first approach in CSS?

Answer

Mobile-first starts with base styles for small screens, then adds media queries for larger screens.

Question

What does the :root selector target?

Answer

:root targets the document's root element (usually <html>), often for CSS variables.

Question

What are CSS custom properties?

Answer

Custom properties (e.g., --color: red) are variables defined with -- and used with var().

Question

How do you use a CSS variable?

Answer

Define it like --main-color: blue, then use it with var(--main-color).

Question

What does the calc() function do?

Answer

calc() performs calculations with units (e.g., width: calc(100% - 20px)).

Question

What is the purpose of the nth-child selector?

Answer

nth-child targets elements based on their position among siblings (e.g., :nth-child(2n)).

Question

What's the difference between :first-child and :first-of-type?

Answer

:first-child targets the first sibling; :first-of-type targets the first of its type.

Question

What does the > selector do?

Answer

The child combinator (>) selects only direct children of a parent element.

Question

What is the + selector?

Answer

The adjacent sibling selector (+) targets an element immediately following another.

Question

What does the ~ selector do?

Answer

The general sibling selector (~) targets all siblings after an element.

Question

What's the purpose of text-overflow: ellipsis?

Answer

text-overflow: ellipsis adds '...' to truncated text when it overflows its container.

Question

What does white-space: nowrap do?

Answer

white-space: nowrap prevents text from wrapping to a new line.

Question

What is the font shorthand property?

Answer

font combines font-style, weight, size, and family (e.g., font: italic bold 16px Arial).

Question

What does line-height control?

Answer

line-height sets the space between lines of text.

Question

What's the difference between relative and absolute units?

Answer

Relative units (e.g., %, rem) scale with context; absolute units (e.g., px, cm) are fixed.

Question

What is the purpose of object-fit?

Answer

object-fit controls how an image or video fits its container (e.g., cover, contain).

Question

What does pointer-events: none do?

Answer

pointer-events: none prevents an element from receiving mouse events.

Question

What's the benefit of using CSS resets?

Answer

CSS resets normalize default browser styles for consistent cross-browser rendering.

Question

What are semantic HTML elements, and why are they important?

Answer

Semantic HTML elements (e.g., <article>, <nav>) describe their meaning or purpose. They're important for accessibility, SEO, and clearer code structure.

Question

How do you create a form in HTML, and what are some common form elements?

Answer

Use the <form> tag with attributes like action and method. Common elements include <input>, <textarea>, <select>, <button>, and <label>.

Question

Explain the difference between block-level and inline elements in HTML.

Answer

Block-level elements (e.g., <div>, <p>) take full width and start on a new line; inline elements (e.g., <span>, <a>) flow within text and take only needed width.

Question

What is the purpose of the <!DOCTYPE> declaration?

Answer

The <!DOCTYPE> declaration tells the browser which HTML version to use, ensuring proper rendering.

Question

What does the <html> tag do?

Answer

The <html> tag is the root element of an HTML document, containing all other elements.

Question

What is the role of the <head> tag?

Answer

The <head> tag contains metadata, like <title>, <meta>, and links to stylesheets or scripts.

Question

What does the <body> tag contain?

Answer

The <body> tag holds the visible content of the page, like text, images, and interactive elements.

Question

What is the purpose of the <title> tag?

Answer

The <title> tag sets the page's title, displayed in the browser tab and used by search engines.

Question

What does the <meta> tag do?

Answer

The <meta> tag provides metadata, like character encoding (e.g., <meta charset='UTF-8'>) or viewport settings.

Question

What is the <div> tag used for?

Answer

The <div> tag is a block-level container for grouping and styling content.

Question

What's the difference between <span> and <div>?

Answer

<span> is an inline container; <div> is a block-level container.

Question

What is the <a> tag used for?

Answer

The <a> tag creates hyperlinks, using the href attribute to specify the URL.

Question

What does the target attribute do in an <a> tag?

Answer

The target attribute specifies where to open the link (e.g., target='_blank' opens in a new tab).

Question

What is the purpose of the <img> tag?

Answer

The <img> tag embeds images, using src for the source and alt for accessibility.

Question

Why is the alt attribute important?

Answer

The alt attribute provides text for screen readers and displays if the image fails to load.

Question

What does the <p> tag do?

Answer

The <p> tag defines a paragraph of text.

Question

What are heading tags?

Answer

Heading tags (<h1> to <h6>) define titles and subheadings, with <h1> being the most important.

Question

What is the <ul> tag used for?

Answer

The <ul> tag creates an unordered (bulleted) list.

Question

What's the difference between <ul> and <ol>?

Answer

<ul> is an unordered list with bullets; <ol> is an ordered list with numbers.

Question

What does the <li> tag do?

Answer

The <li> tag defines a list item within <ul> or <ol>.

Question

What is the purpose of the <table> tag?

Answer

The <table> tag creates a table for tabular data.

Question

What are <tr>, <th>, and <td> tags?

Answer

<tr> defines a table row, <th> a header cell, and <td> a data cell.

Question

What does the colspan attribute do?

Answer

The colspan attribute makes a table cell span multiple columns.

Question

What is the <input> tag used for?

Answer

The <input> tag creates interactive form controls like text fields, checkboxes, or buttons.

Question

What's the difference between type='text' and type='password' in <input>?

Answer

type='text' shows entered text; type='password' masks it with dots.

Question

What does the <label> tag do?

Answer

The <label> tag associates text with a form control, improving accessibility.

Question

What is the purpose of the for attribute in <label>?

Answer

The for attribute links a <label> to an input by matching its ID.

Question

What does the <select> tag do?

Answer

The <select> tag creates a dropdown menu, with <option> tags for choices.

Question

What is the <textarea> tag used for?

Answer

The <textarea> tag creates a multi-line text input field.

Question

What does the <button> tag do?

Answer

The <button> tag creates a clickable button, often for form submission.

Question

What's the difference between <button type='submit'> and <button type='button'>?

Answer

type='submit' submits a form; type='button' is a generic button with no default action.

Question

What is the purpose of the action attribute in <form>?

Answer

The action attribute specifies the URL where form data is sent on submission.

Question

What does the method attribute do in <form>?

Answer

The method attribute defines how form data is sent (e.g., GET or POST).

Question

What is the <header> tag used for?

Answer

The <header> tag defines introductory content or navigation at the top of a page or section.

Question

What does the <footer> tag do?

Answer

The <footer> tag contains closing content, like copyright info, at the bottom of a page or section.

Question

What is the <nav> tag?

Answer

The <nav> tag defines a navigation section, typically for menus or links.

Question

What does the <section> tag do?

Answer

The <section> tag groups related content, often with a heading.

Question

What is the <article> tag used for?

Answer

The <article> tag defines standalone content, like a blog post or news item.

Question

What does the <aside> tag do?

Answer

The <aside> tag contains supplementary content, like sidebars, related to the main content.

Question

What is the purpose of the <main> tag?

Answer

The <main> tag holds the primary content of a page, excluding headers or footers.

Question

What does the id attribute do?

Answer

The id attribute assigns a unique identifier to an element for styling or scripting.

Question

What's the difference between id and class attributes?

Answer

id is unique to one element; class can be applied to multiple elements.

Question

What is the data-* attribute?

Answer

data-* attributes store custom data on elements, accessible via JavaScript.

Question

What does the <script> tag do?

Answer

The <script> tag embeds or links to JavaScript code.

Question

What is the purpose of the async attribute in <script>?

Answer

The async attribute loads a script asynchronously, not blocking HTML parsing.

Question

What does the defer attribute do in <script>?

Answer

The defer attribute loads a script while HTML parses but executes it after parsing completes.

Question

What is the <link> tag used for?

Answer

The <link> tag connects external resources, like CSS files, to the HTML document.

Question

What does the rel attribute do in <link>?

Answer

The rel attribute specifies the relationship between the HTML file and the linked resource (e.g., rel='stylesheet').

Question

What is the purpose of the lang attribute in <html>?

Answer

The lang attribute specifies the document's language (e.g., lang='en' for English).

Question

What does the <iframe> tag do?

Answer

The <iframe> tag embeds another HTML page or content within the current page.