Tuesday, 21 April 2026

React Set 4 - Interview Happy

 Here are all the React interview questions and answers from the transcript:


CHAPTER 1 — BASICS

Q1. What is React? What is the role of React in software development? React is an open-source JavaScript library used for building user interfaces. In a typical web architecture, the frontend server handles what the user sees. React simplifies the creation of single-page applications by using reusable components. Although we already have HTML, CSS, and JavaScript, React simplifies the creation of complex UI applications.


Q2. What are the key features of React? The seven key features are:

  1. Virtual DOM
  2. Component-based architecture
  3. Reusability and composition
  4. JSX (JavaScript XML)
  5. Declarative syntax
  6. Community and ecosystem
  7. React Hooks

Q3. What is DOM? What is the difference between HTML and DOM? DOM stands for Document Object Model. It represents the web page as a tree-like structure that allows JavaScript to dynamically access and manipulate the content and structure of a web page. HTML is just a markup language for reading and writing purposes. In reality, the browser's memory works with the DOM tree. When a user adds or updates an element via JavaScript, a node is added or modified in the DOM tree, which is then converted back to HTML and displayed.


Q4. What is Virtual DOM? What is the difference between DOM and Virtual DOM? Virtual DOM is a concept specific to React (developed by Facebook) to improve application speed. The problem with the real DOM is that even a small change causes the entire page layout to re-render. React solves this by creating an exact copy of the real DOM called the Virtual DOM. When the user interacts, changes are made to the Virtual DOM only. React algorithms then compare (diff) the Virtual DOM with the real DOM and update only the changed parts in the real DOM. This process is called reconciliation.

Differences:

  1. DOM is real and browser-native; Virtual DOM is React-specific.
  2. DOM re-renders the whole page on change; Virtual DOM updates only changed parts.
  3. Virtual DOM makes the web page faster to load.
  4. Virtual DOM is a two-step process (virtual → real) but overall faster.

Q5. What are React components? What are the main elements of a component? In React, a component is a reusable building block for creating user interfaces. A web page is made up of multiple sections (header, menu, footer, etc.) — each is a component. The main elements of a component are:

  1. Import statement
  2. A function or class defining the component logic
  3. A return statement with JSX
  4. An export statement to make the component available in other files

Q6. What is a Single Page Application (SPA)? A Single Page Application is a web application that has only one single web page. When a user performs actions, content is dynamically updated without refreshing or loading a new page. React makes it simple to build SPAs using reusable components. Example: YouTube — the whole page never reloads, only the content/components update.


Q7. What are the five advantages of React?

  1. Component-based architecture — allows creation of reusable components, making development faster and more efficient.
  2. Cross-platform and open-source — free to use, works for web, mobile, and desktop platforms.
  3. Lightweight and fast — due to the Virtual DOM concept.
  4. Large community and ecosystem — maximum jobs, forums, and support available.
  5. Easy UI testing — React libraries make testing the UI straightforward.

Q8. What are the disadvantages of React? React is not a good choice for very simple, mostly static websites. For small applications, the learning curve, project setup, downloading libraries, and planning involved in React can be an overhead. For such cases, plain HTML, CSS, and JavaScript are more appropriate.


Q9. What is the role of JSX in React? JSX stands for JavaScript XML — it looks like HTML/XML but is converted to JavaScript. Three key points:

  1. JSX improves code readability and writability — simpler than writing raw React.createElement() calls.
  2. Browsers only understand JavaScript — Babel converts JSX to JavaScript.
  3. JSX makes development easier — it is simple to read and write.

Q10. What is the difference between declarative and imperative syntax? Declarative syntax (JSX/React): code focuses on what the output should look like. You return HTML-like JSX and the result is self-explanatory — it does not focus on step-by-step programming. Imperative syntax (pure JavaScript): focuses on step-by-step instructions — create element, assign text, append to DOM, etc. React's declarative syntax is a key feature that makes React code simpler and more readable.


CHAPTER 2 — BASICS (CONTINUED)

Q11. What is the arrow function expression in JSX? Arrow function expression is a combination of arrow function syntax and function expression. Instead of using the function keyword and a function name, you assign an arrow function to a variable. Example: const MyComponent = (props) => { return <div/>; }. The function name is not needed because you use the variable name to call or export it. This is now the recommended approach for declaring React components.


Q12. How to set up a React project? Five steps:

  1. Install Node.js.
  2. Install a code editor like VS Code.
  3. Open terminal and run: npx create-react-app my-app
  4. Open the created folder in VS Code.
  5. Run npm start in the terminal — the browser auto-loads your first React app.

Q13. How does the React app load and display components in the browser? Flow:

  1. User opens browser → request goes to React server → index.html is returned (the single HTML page).
  2. index.html loads the React libraries, which load index.js (the JavaScript entry point).
  3. index.js calls the App component (root component).
  4. The App root component replaces the root element (div#root) in index.html with all child components.
  5. The result is displayed in the browser.

Q14. What is the difference between React and Angular? Similarities: both used to create SPA web applications using components.

Differences:

  1. React is a JavaScript library; Angular is a complete UI framework.
  2. React uses Virtual DOM (faster); Angular uses real DOM.
  3. React is lightweight and smaller in size; Angular is bigger.
  4. React depends on external libraries for complex features (more code to write); Angular has built-in routing, forms, HTTP, etc.
  5. React is simpler to learn and more popular; Angular is slightly harder (requires TypeScript, OOP concepts).

Q15. What are other popular JS frameworks other than React? Popular frontend frameworks/libraries besides React: Angular, Vue.js, AngularJS, Backbone.js, Ember.js. React is currently the most popular.


Q16. Whether React is a library or a framework? What is the difference? React is commonly referred to as a JavaScript library. A library provides reusable functions that you import and use — you control the structure. A framework is a complete package that defines its own rules and structure that developers must follow (e.g., Angular). React is a library, though it is increasingly doing things a framework can do.


Q17. How does React provide reusability and composition? React provides both through its component-based architecture. Reusability: once a component is created, it can be reused in different parts of the application and across multiple projects. Composition: creating new, larger components by combining existing small components. The advantage is that components can be created independently by different developers, and changes to one component do not impact the rest of the application.


Q18. What are state, stateless, stateful, and state management? State refers to the current data of a component (e.g., a count variable set to 0). Stateless: a component that cannot render state changes in the UI — even if data updates, the UI does not reflect it. Stateful (state management): when a user performs an action, the React application updates and renders the data/state in the UI immediately. To make a component stateful, use React Hooks or component lifecycle methods.


Q19. What are props in JSX? Props (short for properties) are a way to pass data from a parent component to a child component. In the parent, data is passed as attributes on the child component tag. In the child, it is received via the props parameter and accessed as props.name, props.purpose, etc.


CHAPTER 3 — FILES AND FOLDERS

Q20. What is npm? What is the role of the node_modules folder? npm (Node Package Manager) is used to manage dependencies for a React project, including the React library itself. It downloads and installs all required libraries at once. The node_modules folder contains all the dependencies of the project including the React libraries. You should never modify this folder manually.


Q21. What is the role of the public folder in React? The public folder contains static assets served directly to the user's browser, such as images, fonts, and the index.html file. Static means no user interaction, no JavaScript logic, no API data fetching — just fixed content like favicon, index.html, and images.


Q22. What is the role of the src folder in React? The src (source) folder is where all the source code developed by the developer is placed. It is the most important folder from a developer's point of view. All components and dynamic application logic live here. It is responsible for the dynamic changes in the web application.


Q23. What is the role of the index.html page in React? index.html is the single page in a React single-page application. It is a static HTML file inside the public folder. When a user opens the React website, this is the first page that loads. It contains a <div id="root"> which is replaced dynamically by the components from index.js. The title and meta tags remain as-is; only the root div is replaced.


Q24. What is the role of the index.js file in React? index.js is the JavaScript entry point for the React application. It imports the ReactDOM library from react-dom/client. It uses ReactDOM.createRoot() to get a reference to the root element from index.html. It then calls .render() to render the App component in place of the root element. Definition: index.js replaces the root element of index.html with the newly rendered component using the ReactDOM library.


Q25. What is the role of the App.js file in React? App.js contains the root component (App) of the React application. The App component acts as a container for all child components — it is like the parent of all components. Three key points:

  1. App.js contains the root App component.
  2. App component is a container for all child components.
  3. App.js defines the structure, layout, and routing of the application.

Q26. What is the role of the function and return statements inside App.js? The function keyword defines a JavaScript function that represents the React component. It is a placeholder containing all the logic of the component. The function takes props as arguments and returns JSX. The return statement returns the JSX elements that will be displayed in the browser. Without a return, nothing is rendered to the DOM.


Q27. Can we have a function without a return statement inside App.js? Yes. A function without a return statement is valid — the component renders nothing in the UI. A common real-world use case is for logging or error-tracking components that only perform side effects (like console.log) without rendering any element.


Q28. What is the role of 'export default' inside App.js? The export default statement makes the component available for import in other files. If you remove it, the import statement in other files (like index.js) will fail and throw an error because the component is no longer available for external use.


Q29. Does the file name and component name have to be the same in React? No, they can be different. However, it is not recommended — keeping them the same is a best practice for easier code organization and readability.


CHAPTER 4 — JSX

Q30. What are the advantages of JSX?

  1. Improved readability and writability — simpler than raw JavaScript React code.
  2. Better error checking / type safety — JSX shows errors (red underlines) in the editor in advance; raw JavaScript does not.
  3. Supports JavaScript expressions — you can embed JS expressions inside curly braces {}.
  4. Improved performance.
  5. Code reusability.

Q31. What is Babel? Babel is a library (included in node_modules, installed by npm) that transpiles JSX syntax into regular JavaScript which browsers can understand. Browsers like Chrome and Edge cannot read JSX directly — Babel converts it to valid JavaScript first. Definition: Babel is a transpiler used in React to convert JSX to JavaScript.


Q32. What is the role of fragments in React? In JSX, all elements must be enclosed inside a common root/parent element. If you have sibling elements without a parent, you get a compilation error. Wrapping in a div adds an unwanted DOM node and can break layout. The proper solution is to use React Fragment: <React.Fragment>...</React.Fragment> or the shorthand <>...</>. Fragments group children without adding any extra nodes to the DOM. Definition: a fragment is a way to group a list of children without adding extra nodes to the DOM.


Q33. What is a spread operator in JSX? The spread operator (...) is used to expand or spread an array or object. In React, when passing multiple properties from a parent to a child component, you can create a props object and use the spread operator to pass all properties at once: <ChildComponent {...propsObject} />. The child accesses them the same way as normal props.


Q34. What are the types of conditional rendering in JSX? Four types:

  1. if/else — traditional conditional, good for multiple statements.
  2. Ternary operator — single-line: condition ? 'true' : 'false'.
  3. AND operator (&&) — returns the statement if condition is true; returns null if false (no else option).
  4. Switch statement — for multiple conditions/cases with a default fallback.

Q35. How to iterate over a list in JSX? What is the map method? The map() method is a JavaScript function usable in JSX that iterates over an array and returns a new array with each element transformed. It accepts a callback function (which can be an arrow function) that processes each element. Example: numberList.map((number) => number * 2) returns a new array with each number doubled. Definition: the map method allows you to iterate over an array and modify its elements using a callback function.


Q36. Can a browser read a JSX file? No. Browsers cannot directly interpret or understand JSX. Babel converts JSX into equivalent JavaScript code that browsers can understand.


Q37. What is a transpiler? What is the difference between compiler and transpiler? Transpiler: a tool that converts source code from one high-level language (e.g., JSX) to another high-level language (e.g., JavaScript). Example: Babel. Compiler: a tool that converts a high-level language (e.g., Java) to a lower-level language (e.g., machine code). Key difference: compiler = high-to-low level; transpiler = high-to-high level.


Q38. Is it possible to use JSX without React? Yes, technically possible by creating your own transpiler like Babel. However, it is not recommended because JSX is tightly integrated with React and relies on many React-specific features.


CHAPTER 5 — COMPONENTS (FUNCTIONAL & CLASS)

Q39. What are the types of React components? Two types:

  1. Functional components — defined as a JavaScript function, originally stateless but can now manage state using Hooks.
  2. Class components — defined as a JavaScript class, stateful by nature using lifecycle methods and this.state.

Q40. What are functional components? Functional components are the standard way of declaring components using a JavaScript function (regular or arrow function). Two key points:

  1. Defined as JavaScript functions.
  2. Originally stateless but can now manage state using React Hooks.

Q41. How do you pass data between functional components in React? Using props (properties). Props are a way to pass data from a parent component to a child component. The parent passes data as attributes on the child component tag, and the child receives and uses it via its props parameter.


Q42. What is prop drilling in React? Prop drilling is the process of passing the same data (via props) through multiple layers of components — from a top parent component down through intermediate components to a deeply nested child — even when intermediate components do not need the data. It is called "drilling" because you drill down through layers.


Q43. Why should you avoid prop drilling? In how many ways can you avoid it? Why avoid it:

  1. Difficult maintenance — changes in data flow require updates across multiple components.
  2. Increased complexity — reduces code readability.
  3. Debugging challenges — tracking data through multiple layers is hard.

Five ways to avoid prop drilling:

  1. Context API
  2. Redux
  3. Component composition
  4. Callback functions
  5. Custom Hooks

Q44. What are class components in React? Class components are declared using a JavaScript class that extends React's Component class. Key points:

  1. Defined using JavaScript classes (extends Component).
  2. Stateful — can manage local state using this.state.
  3. Have a render() method responsible for returning JSX.
  4. Exported like functional components for use in other files.

Q45. How to pass data between class components in React? Using this.props. In the parent class component, pass data as an attribute on the child component tag. In the child class component, access it via this.props.attributeName. Definition: this.props is used in child class components to access properties/data passed from the parent component.


Q46. What is the role of the 'this' keyword in class components? The 'this' keyword is a reference to the current instance of the class. In class components, it refers to the instance of the component class. It is used to access props (this.props), state (this.state), and other class methods. Without 'this', props and state cannot be related to their class. Short answer: 'this' is used to refer to the instance of the class.


Q47. What are the five differences between functional and class components?

  1. Syntax: functional = JavaScript function; class = JavaScript class.
  2. State: functional originally stateless (now uses Hooks); class uses this.state.
  3. Lifecycle methods: functional components do not have lifecycle methods; class components do.
  4. Readability: functional = more readable, concise, simple; class = more verbose/complex.
  5. 'this' keyword: functional has no 'this'; class uses 'this' for accessing properties. Bonus: functional has no render() method; class requires render() to return JSX.

CHAPTER 6 — ROUTING

Q48. What is routing and router in React? Routing means navigation — React provides a way to navigate from one component to another without refreshing the page. The URL updates and the component changes without a full page reload. Definition: routing allows you to create a SPA with navigation without a full page refresh. React Router is a library for handling routing in React — it enables navigation and rendering of different components based on the URL.


Q49. How to implement routing in React? Steps:

  1. Install react-router-dom using npm.
  2. In App.js, import Routes, Route, and Link from the library.
  3. Use the Link component for navigation items.
  4. Define routes using the Route component with path and element attributes.
  5. In index.js, wrap the App component inside the BrowserRouter component.

Q50. What are the roles of Routes and Route components in React Router? Routes: a container component that holds a collection of Route components — just a wrapper for multiple Routes. Route: defines a path and specifies which component/element to render when the URL matches that path. Example: <Route path='/about' element={<About />} /> renders the About component when the URL is /about.


Q51. What are route parameters in routing? Route parameters are dynamic values passed as part of the URL path. Example: <Route path='/user/:userId' element={<UserProfile />} /> — here userId is a route parameter. Definition: route parameters are a way to pass dynamic data/values to a component as part of the URL path.


Q52. What is the role of the Switch component in React Router? Switch is a container for multiple Route components. When multiple routes have similar or overlapping paths, Switch executes only the first matched route and ignores the rest. It is commonly used to handle 404 / Not Found routes as a default fallback.


Q53. What is the role of the exact prop in routing? By default, a route with path='/about' also matches '/about/team', '/about/contact', etc. Adding the exact prop makes the route match only the exact path '/about' and nothing else. Definition: the exact prop is used with the Route component to match exactly the provided path.


CHAPTER 7 — HOOKS (USESTATE & USEEFFECT)

Q54. What are React Hooks? Which are the top React Hooks? React Hooks are inbuilt functions provided by React that allow functional components to use state and lifecycle features. Before Hooks, class component lifecycle methods were used. Hooks are simpler and designed for functional components. They must be imported from the React library.

Top Hooks: useState, useEffect, useContext, useReducer, useCallback, useMemo, useRef, useLayoutEffect.


Q55. What is the role of the useState Hook and how does it work? useState is a React Hook for managing state in functional components. Working:

  1. Import useState from React.
  2. Call useState(initialValue) — it returns an array of two elements via array destructuring: [currentStateValue, setterFunction].
  3. The setter function (e.g., setCount) updates the state and triggers a re-render.
  4. useState is called only once when the component first loads; after that, only the setter function is called on updates.

Array destructuring assigns the two array elements to individual variables. The setter function is a React library function returned by useState that maintains the state.


Q56. What is the role of the useEffect Hook, how does it work, and what is its use? useEffect is used to perform side effects in functional components. Side effects are operations (e.g., data fetching from an API, subscriptions) that happen after the component has been initially rendered. useEffect accepts two parameters:

  1. An effect function — contains the side effect code (e.g., fetch data from API).
  2. A dependency array.

The effect function runs after the component renders. Key points:

  1. useEffect is called after the component renders.
  2. It accepts an effect function and a dependency array.

Q57. What is the dependency array in useEffect? The dependency array is the second parameter of useEffect. It contains values (dependencies) that, when changed, cause the effect function to re-run. Example: [userId] as the dependency — when userId changes, the data is re-fetched from the API. It is an array because you may have multiple dependencies.


Q58. What is the meaning of an empty array [] in useEffect? An empty array [] as the second parameter means the effect function runs only once — when the component first mounts. Because there are no dependencies, there is nothing to trigger a re-run. Use this when the side effect only needs to happen once (e.g., fetching fixed data).


CHAPTER 8 — HOOKS (USECONTEXT)

Q59. What is the role of the useContext Hook? useContext provides a way to pass data from a parent component to child components without using props (avoiding prop drilling). How it works:

  1. Create a context object: const MyContext = createContext().
  2. In the parent, wrap child components in MyContext.Provider and set its value prop.
  3. In any child, call useContext(MyContext) — it returns the context value directly.

The alternative is using MyContext.Consumer, but useContext is simpler and preferred.


Q60. What is the createContext method? What are provider and consumer properties?

  1. createContext() returns an object with Provider and Consumer properties.
  2. The Provider property provides the context value to all its child components.
  3. The useContext method or the Consumer property can be used to consume/get the context value in child components.

Q61. When to use the useContext Hook instead of props? Use useContext instead of props when you want to avoid prop drilling and access context values directly within deeply nested components. For one level of parent-child, props are simple and fine. For multiple levels, useContext is better.

Real-world scenarios: theme switching, localization, centralized configuration, user preferences, notification systems.


CHAPTER 9 — COMPONENT LIFECYCLE METHODS

Q62. What are component lifecycle phases? Three lifecycle phases:

  1. Mounting phase — component is created and inserted into the DOM for the first time; methods execute before the component is rendered.
  2. Updating phase — component re-renders when state or props change.
  3. Unmounting phase — component is being removed from the DOM (e.g., replaced by another component).

Q63. What are component lifecycle methods? Each phase has methods that execute in sequence.

Mounting phase (in order): constructor → static getDerivedStateFromProps → render → componentDidMount. Updating phase (in order): static getDerivedStateFromProps → shouldComponentUpdate → render → getSnapshotBeforeUpdate → componentDidUpdate. Unmounting phase: componentWillUnmount.

Definition: component lifecycle methods are special methods that get called at various stages of a component's life.


Q64. What are constructors in class components? When to use them? The Constructor is the first method of the mounting phase. It is a specialized function that is invoked automatically when the component is called — no need to call it explicitly. Use the Constructor for:

  1. Initializing the component state (this.state = { count: 0 }).
  2. Performing mandatory setup before the component renders.

The component will not render until the Constructor code completes.


Q65. What is the role of the super keyword in the constructor? The super keyword calls the Constructor of the parent class (Component from React). Rule: before the child class Constructor runs, the parent class Constructor must run first — super() enforces this. Removing super() will break the application. Conclusion: super calls the parent class Constructor to ensure the parent's initialization logic runs before the child's.


Q66. What is the role of the render method in the component lifecycle? The render method is responsible for displaying (returning) JSX elements in the UI/DOM. It appears in both the mounting phase (first render) and the updating phase (re-renders after state/props change). Without render(), nothing is displayed in the browser. Definition: the render method returns the React elements that will be rendered to the DOM.


Q67. How can state be maintained in a class component? Two-step process:

  1. Set initial state in the Constructor: this.state = { count: 0 }.
  2. Use this.setState() to update the state — it increments the count and triggers a re-render.

this.setState() is the React Library function that updates state. this.state is used to read and render the current value in the DOM.


Q68. What is the role of the componentDidMount method? componentDidMount is the last method of the mounting phase (runs after render). It is used for side effects — operations that run after the component is already rendered to the DOM, such as fetching external API data or setting up subscriptions. Conclusion: componentDidMount is called after the component has been rendered to the DOM and is mostly used for side effects like data fetching.


CHAPTER 10 — CONTROLLED COMPONENTS

Q69. What are controlled components in React? A controlled component is a component whose form elements (input fields, checkboxes, etc.) are controlled by the application's state. Example: an input field whose value is stored in state and updates via an onChange event — every keystroke updates the state and the state drives the input value.


Q70. What are the differences between controlled and uncontrolled components? Controlled:

  1. Uses application state to save changes.
  2. State is updated on every event.
  3. Recommended best practice for forms.

Uncontrolled:

  1. No state management — values accessed directly via useRef.
  2. Less re-rendering.
  3. Useful when integrating with non-React libraries.
  4. Less commonly considered a best practice.

Q71. What are the characteristics of a controlled component?

  1. State control — form element value is stored in component state.
  2. Event handling — changes trigger an event (e.g., onChange).
  3. State update — the event handler updates the state with the new value.
  4. Rendering — component re-renders with the updated state, and the form element reflects the new value.

Q72. What are the advantages of using controlled components in React forms?

  1. Single source of truth — state is the single source that provides values to all form elements; it cannot be directly manipulated.
  2. Predictable and synchronized updates — easier to implement form validation, dynamic rendering, and lifecycle integration.
  3. Better control and maintainability compared to uncontrolled components.

Q73. How to handle forms in React? The preferred and recommended approach for handling forms in React is by using controlled components.


Q74. How can you handle multiple input fields in a controlled form? Maintain separate state variables for each input field and update them individually using the onChange event handler.


Q75. How do you handle form validation in a controlled component? By using conditional rendering based on the state — validate the input values before updating the state. If the value meets the condition, update the state; otherwise, do not.


Q76. In what scenarios might using uncontrolled components be advantageous? Uncontrolled components can be beneficial when:

  1. Integrating with non-React libraries.
  2. Dealing with forms where controlled components are not possible.

CHAPTER 11 — CODE SPLITTING

Q77. What is code splitting in React? Without code splitting: all files are bundled together and sent to the browser in one single request. With code splitting: each file/chunk is loaded on demand — CSS only when needed, JS only when needed, etc. Definition: code splitting is a technique to split the JavaScript bundle into smaller chunks which are loaded on demand.


Q78. How to implement code splitting in React? Three steps:

  1. Use React.lazy() to lazily import components: const CodeSplit = React.lazy(() => import('./CodeSplit')).
  2. Wrap components with Suspense to handle loading: <Suspense fallback={<div>Loading...</div>}><CodeSplit /></Suspense>.
  3. Install and configure webpack for dynamic imports.

lazy() loads the component only when it is actually needed. Until then, Suspense shows the fallback UI.


Q79. What is the role of lazy and Suspense in React? React.lazy: a function that allows you to load a component lazily — it enables code splitting by importing a component asynchronously, only when needed. Suspense: a component that displays a fallback UI while the lazily loaded component is being fetched. Once loaded, the component replaces the fallback UI.


Q80. What are the pros and cons of code splitting? Pros:

  1. Faster initial load time — only loads necessary code.
  2. Optimized bandwidth usage — less data transferred.
  3. Improved caching — smaller focused chunks are easier to cache.
  4. Parallel loading — multiple chunks can load simultaneously.
  5. Easier maintenance — more modular and independent code.

Cons:

  1. Increased project complexity.
  2. Tooling dependency (webpack, Babel configuration).
  3. Potential runtime errors.
  4. Increased number of HTTP requests.
  5. Learning curve for new developers.

Q81. What is the role of the import() function in code splitting? The import() function returns a promise that allows dynamic loading of modules.


Q82. What is the purpose of the fallback property in Suspense? The fallback property provides a loading indicator or UI while the dynamically imported component is being loaded.


Q83. Can you dynamically load CSS files using code splitting in React? Yes. Using dynamic import for CSS files allows you to load styles on demand along with the corresponding components.


Q84. How do you inspect and analyze the generated chunks in a React application? Use tools like Webpack Bundle Analyzer to analyze the size and composition of the generated chunks.


CHAPTER 12 — ADVANCED / MISCELLANEOUS

Q85. What is a Higher Order Component (HOC) in React? A Higher Order Component is a component that takes another component as an argument and adds extra features/functionality to it. Example: HOCLogger(HocUser) — HOCLogger adds logging functionality. When HocUser is exported through HOCLogger, the HOC's extra features run first, then the main component runs. Real-world use: error logging. HOCs are reusable across multiple components.


Q86. What are the five ways to style React components?

  1. Inline styles — style attribute directly on the element as a JS object.
  2. CSS style sheets — separate .css files imported into components.
  3. CSS modules — scoped .module.css files to avoid global style conflicts.
  4. Global style sheets — a single global CSS file.
  5. CSS Frameworks — like Bootstrap, Tailwind, etc.

Q87. What are the differences between React and React Native?

  1. React is a library; React Native is a framework.
  2. React builds web interfaces; React Native builds mobile apps.
  3. React runs on web browsers; React Native runs on iOS and Android.
  4. React uses HTML and CSS for UI; React Native uses native UI components (View, Text, etc.).
  5. React is deployed as a web app; React Native is deployed through the App Store or Google Play.

Q88. What is GraphQL? GraphQL is a query language for APIs and a runtime for executing those queries with your existing data. Developed by Facebook. React components can use GraphQL queries to fetch data required for rendering. React and GraphQL are often used together because both are developed by Facebook and are compatible with each other.


Q89. What are the top three ways to achieve state management in React? When to use what?

  1. useState Hook — use for simple, single-component level state. Best for small components with isolated state. It is lightweight and built into React.
  2. Context API — use to avoid prop drilling for sharing global data across multiple components. Good for small to medium-sized applications.
  3. Redux — use for large-scale applications with complex state. It has a centralized store and actions providing a predictable state management pattern, ideal for scalability.

Q90. How can you implement authentication in a React application? Using JWT (JSON Web Token) authentication — 8 steps:

  1. User enters username/password in browser.
  2. Credentials sent to API via POST request.
  3. API validates credentials.
  4. If valid, API creates a JWT token and sends it back to the client.
  5. Client stores JWT in browser's local storage.
  6. For subsequent requests, JWT is sent in the request header.
  7. API validates the token signature.
  8. If valid, API sends data; client displays it.

The user only logs in once — after that, the token handles all subsequent authentication.


Q91. What is the use of React Profiler? React Profiler is a set of tools that allows developers to profile/analyze the performance of a React application. Wrap the code to be measured inside a Profiler component with an id and an onRender callback. The onRender function logs start time, execution time, and end time of the code execution, helping identify performance bottlenecks.


Q92. What is the difference between Fetch and Axios for API calls in React?

  1. Fetch is a built-in JavaScript function requiring no extra libraries; Axios is a third-party library requiring installation and import.
  2. Fetch returns a Promise; Axios also uses Promises but additionally supports interceptors — useful for adding tokens, logging, and error handling across multiple requests.

When to use: if HTTP requests are simple, use Fetch. If you need advanced control over interceptors for multiple requests/responses, use Axios.


Q93. What are the popular testing libraries for React? Four most popular testing libraries:

  1. Jest
  2. React Testing Library
  3. Enzyme
  4. Cypress

Q94. How can you optimize performance in a React application?

  1. Memoization — use useMemo and useCallback to avoid unnecessary recalculations.
  2. Optimize renders — use React.Fragment to avoid unnecessary wrapper DOM nodes.
  3. Lazy loading — use React.lazy() to reduce initial bundle size.
  4. Code splitting — divide the app into smaller chunks loaded on demand.
  5. Optimize images and assets — compress images, use responsive images, and lazy load images to reduce bandwidth.

Q95. Explain reactive programming with an example. Reactive programming is a programming approach that focuses on reacting to changes and events in a declarative and asynchronous manner. Example: Google's autocomplete — as you type, Google continuously captures keyboard events and fetches/displays suggestions without blocking the UI. Declarative means writing code for what you want to achieve (not step-by-step). Asynchronous means fetching happens without blocking user input.


Q96. In how many ways can we implement reactive programming in React? Ways to handle reactive programming in React:

  1. State and Props
  2. React Hooks
  3. Event handling
  4. Context API
  5. Redux
  6. Component lifecycle methods
  7. async/await
  8. RxJS and Observables

If you are using event handling with state management techniques like Hooks or Redux, you are likely already doing reactive programming in your project.


Q97. How to pass data from a child component to a parent component in React? Using callback functions:

  1. Define a callback function in the parent that accepts data as an argument.
  2. Pass the callback function as a prop to the child component.
  3. In the child, define a function (e.g., dataToParent) that calls the received callback with the data (e.g., input field value).
  4. When triggered (e.g., button click), the callback executes in the parent context and receives the data.

Definition: the parent provides a callback function to the child, and the child invokes this callback to pass data back to the parent.


That covers all the questions and answers from the transcript across all chapters.

Share:

Javascript interview questions

 Here are all the questions and answers from the transcript:


JavaScript Basics

Q1: What is JavaScript? What is the role of the JavaScript engine?

JavaScript is a programming language used for converting static web pages into interactive and dynamic web pages. Every browser has a JavaScript engine that executes JavaScript code. Examples: V8 (Chrome), SpiderMonkey (Firefox), JavaScriptCore (Safari), Chakra (Edge). The JavaScript engine is a program present in the web browser that executes JavaScript code.


Q2: What are client-side and server-side?

A client is a device, application, or software component that requests and consumes services or resources from a server. A server is a device, computer, or software application that provides services, resources, or functions to clients. The browser on the client can run HTML, JavaScript, and CSS. Servers can run languages like C#, Java, PHP, Node, etc.


Q3: What is scope in JavaScript?

Scope determines where variables are defined and where they can be accessed. There are three types:

  • Global scope – variable defined at the top of the program, accessible everywhere.
  • Function scope – variable defined inside a function, not accessible outside it.
  • Block scope – variable defined inside a block (if, else, etc.), not accessible outside that block.

Q4: What is the type of a variable when declared without var, let, or const?

var is the implicit type. When a variable is declared without any keyword, JavaScript treats it as var, making it function-scoped and accessible outside blocks.


Q5: What is hoisting in JavaScript?

Hoisting is a JavaScript behavior where functions and variable declarations are moved to the top of their respective scopes during the compilation phase. This allows functions and var variables to be used before they are declared. Note: let does not allow hoisting.


Q6: What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format consisting of key-value pairs. It is used to exchange data between web APIs and is more popular than XML due to its simplicity.


Variables & Data Types

Q7: What are variables? What is the difference between var, let, and const?

Variables store or hold data.

  • var – function-scoped; accessible outside blocks within the same function.
  • let – block-scoped; only accessible within the block it is defined; more popular due to clarity.
  • const – block-scoped; can only be assigned once; value cannot be changed after first assignment.

Q8: What are data types in JavaScript?

A data type determines the type of a variable. JavaScript automatically identifies the type by the value assigned. Types include: number, string, boolean, undefined, null (primitive), and object, array, function, date, regex (non-primitive).


Q9: What is the difference between primitive and non-primitive data types?

Primitive Non-Primitive
Examples number, string, boolean, undefined, null object, array, function, date, regex
Values Single value only Multiple values
Mutability Immutable Mutable
Complexity Simple Complex

Primitive types create a new memory address when "modified." Non-primitive types can be modified at the same memory location.


Q10: What is the difference between null and undefined?

  • undefined – variable declared but not assigned a value; JavaScript automatically initializes it as undefined. Use when you don't have the value yet but will get it after some logic.
  • null – variable intentionally assigned a null value (no data type). Use when you are sure no value will be assigned soon.

Q11: What is the use of the typeof operator?

The typeof operator is used to determine the type of a variable. Useful for validating data received from external sources or APIs.

typeof 42        // "number"
typeof "hello"   // "string"
typeof true      // "boolean"

Q12: What is type coercion in JavaScript?

Type coercion is the automatic conversion of values from one data type to another during certain operations or comparisons. Example: "42" + 1"421" (number converted to string). Uses: string/number concatenation, comparison operators.


Operators & Conditions

Q13: What is operator precedence?

Operators with higher precedence are evaluated first. Order: brackets → division → multiplication → addition → subtraction (like BODMAS). Example: (a - b) * c + a – bracket is resolved first.


Q14: What is the difference between unary, binary, and ternary operators?

  • Unary – operates on one operand (e.g., -a, ++a)
  • Binary – operates on two operands (e.g., x + y)
  • Ternary – operates on three operands using ? and : (condition ? valueIfTrue : valueIfFalse)

Q15: What is short-circuit evaluation in JavaScript?

Short-circuit evaluation stops execution as soon as the result can be determined without evaluating remaining sub-expressions.

  • AND (&&) – if the left side is false, the right side is not evaluated.
  • OR (||) – if the left side is true, the right side is not evaluated.

Q16: What are the types of conditional statements in JavaScript?

  1. if-else – most common; evaluates multiple conditions.
  2. Ternary operator – shorthand for simple if-else (condition ? val1 : val2).
  3. Switch statement – checks a variable against multiple cases; uses break to exit; default runs when no case matches.

Q17: What is the difference between == (double equals) and === (triple equals)?

  • == (loose equality) – performs type coercion before comparison; 1 == "1" is true.
  • === (strict equality) – no type coercion; compares value AND type; 1 === "1" is false. Preferred in real applications for more accurate comparisons.

Q18: What is the difference between the spread and rest operators?

Both use three dots (...) but serve different purposes:

  • Spread operator – expands/spreads elements of an iterable (array/string) into individual elements. Uses: copying arrays, merging arrays, passing multiple arguments to a function.
  • Rest operator – used in function parameters to collect remaining arguments into an array.

Arrays

Q19: What are arrays in JavaScript? How do you get, add, and remove elements?

An array is a data type that allows you to store multiple values in a single variable. Key methods:

  • Add: push() (end), unshift() (start)
  • Remove: pop() (last), shift() (first)
  • Get/Filter: filter(), map(), concat()

Q20: What is the indexOf method of an array?

indexOf gets the index of a specified element in the array. Returns the index number (0-based).


Q21: What is the difference between the find and filter methods?

  • find() – returns the first element that satisfies a condition.
  • filter() – returns an array of all elements that satisfy the condition.

Q22: What is the slice method of an array?

slice(startIndex, endIndex) gets a subset of the array from the start index to the end index. The element at the end index is NOT included.


Q23: What is the difference between push and concat methods?

  • push() – modifies the original array by adding elements to the end.
  • concat() – creates and returns a new array with added elements; original array remains unchanged.

Q24: What is the difference between pop and shift methods?

  • pop() – removes and returns the last element of the array.
  • shift() – removes and returns the first element of the array.

Q25: What is the splice method of an array?

splice(startIndex, deleteCount, ...itemsToAdd) is used to add, remove, or replace elements in an array. It is the most versatile array method. Use when you have the start index. Other array methods are used when you don't.


Q26: What is the difference between slice and splice?

  • slice – gets a subset of the array (start to end, end not included); does not modify original.
  • splice – adds, removes, or replaces elements based on start index; modifies the original array.

Q27: What is the difference between map and forEach?

  • map() – iterates each element, modifies it, and returns a new array with modified values.
  • forEach() – iterates each element and performs an action without creating a new array. Original array is unchanged.

Q28: How do you sort and reverse an array?

  • array.sort() – sorts the array (works directly with strings/characters, needs custom logic for numbers).
  • array.reverse() – reverses the array.

Q29: What is array destructuring in JavaScript?

Array destructuring allows you to extract elements from an array and assign them to individual variables in a single statement. Introduced in ES6.

const [first, second, third] = fruits;

Q30: What are array-like objects in JavaScript?

Array-like objects have indexed elements and a length property similar to arrays, but do not have all array methods (like push, pop, filter). Examples: strings, arguments object, HTMLCollection.


Q31: How do you convert an array-like object into an array?

Three ways:

  1. Array.from(arrayLikeObject)
  2. Spread syntax: [...arrayLikeObject]
  3. Array.prototype.slice.call(arrayLikeObject)

Loops

Q32: What is a loop? What are the types of loops in JavaScript?

A loop is a programming construct to run a piece of code repeatedly until a certain condition is met. Types: for, while, do...while, for...of, for...in.


Q33: What is the difference between while and for loop?

  • for loop – better when you have initialization, a condition, and an increment (number-based iteration). Everything in one line.
  • while loop – better when only a condition is required, with no initialization or increment needed.

Q34: What is the difference between while and do...while loops?

  • while – checks condition first; if false, loop body never executes.
  • do...while – executes the loop body at least once, then checks the condition.

Q35: What is the difference between break and continue?

  • break – terminates the loop entirely.
  • continue – skips the current iteration and moves to the next one.

Q36: What is the difference between for and for...of loops?

  • for loop – general-purpose; requires initialization, condition, and increment; more complex.
  • for...of loop – simpler and shorter; specifically for iterating arrays and objects; no index needed.

Q37: What is the difference between for...of and for...in loops?

  • for...of – iterates over values of an iterable (array, string); accesses each value directly.
  • for...in – iterates over the keys/properties of an object; access values using the key as index.

Q38: What is the purpose of the forEach method? Compare it with for...of and for...in.

forEach is an array/object method that iterates each element and performs an action. It can do what both for...of (for arrays) and for...in (for objects via Object.keys/Object.values) do, but with slightly more convenient syntax. However, forEach does not support break or continue.


Q39: When to use for...of loop vs forEach method?

  • Use for...of when you need more control, such as using break or continue inside the loop.
  • Use forEach only when you want to iterate over every single element with no interruptions needed.

Functions

Q40: What are functions in JavaScript? What are the types of functions?

A function is a reusable block of code that performs a specific task. Types: named functions, anonymous functions, function expressions, arrow functions, IIFE, callback functions, higher-order functions.


Q41: What is the difference between named and anonymous functions?

  • Named functions – have a name identifier; used for complex/reusable logic at multiple places.
  • Anonymous functions – have no name; cannot be called directly by name; used for simple, single-use logic.

Q42: What is a function expression in JavaScript?

A function expression is a way to define a function by assigning it to a variable. Usually used with anonymous functions.

const add = function(x, y) { return x + y; };

Q43: What are arrow functions in JavaScript?

Arrow functions (fat arrow functions) are a simpler and shorter way of defining functions. They use => syntax. No need for the return keyword in single-expression functions. They make code shorter and more concise.

const add = (x, y) => x + y;

Q44: What are callback functions? What is their use?

A callback function is a function that is passed as an argument to another function. Use: allows passing different logic (add, subtract, multiply) to a single display function, making code cleaner and more structured.


Q45: What is a higher-order function in JavaScript?

A function is a higher-order function if it:

  1. Takes one or more functions as arguments (receives a callback), OR
  2. Returns a function as a result.

Q46: What is the difference between arguments and parameters?

  • Parameters – placeholders defined in the function declaration.
  • Arguments – the actual values passed to the function when it is called.

Q47: In how many ways can you pass arguments to a function?

  1. Positional arguments – pass values directly in order.
  2. Named arguments – pass an object with named keys.
  3. Arguments object – use the arguments keyword inside the function to access passed values by index.

Q48: How do you use default parameters in a function?

Default parameters allow you to specify default values for function parameters. If no argument is passed, the default value is used; if an argument is passed, it overrides the default.

function greet(name = "Happy") { ... }

Q49: What is the purpose of event handling in JavaScript?

Event handling is the process of responding to user actions on a web page. The addEventListener method attaches an event name and the function (handler) to execute when that event occurs. Common events: click, mouseover, keydown, keyup, submit, focus, blur, change, load, resize.


Q50: What are first-class functions in JavaScript?

A language has first-class functions if functions are treated like variables — they can be assigned to variables, passed as arguments, and returned from other functions. JavaScript supports all of these, so functions in JavaScript are first-class functions.


Q51: What are pure and impure functions in JavaScript?

  • Pure function – always produces the same output for the same input; cannot modify external state; no side effects.
  • Impure function – can produce different outputs for the same input; can modify external state (side effects).

Q52: What is function currying in JavaScript?

Currying transforms a function with multiple arguments into a nested series of functions, each taking a single argument. Benefits: reusability, modularity, and specialization — complex functions can be broken into small reusable functions.


Q53: What are call, apply, and bind in JavaScript?

All three are used to control how a function is invoked and what context (this) it operates in:

  • call – invokes the function with a specified this context and arguments passed individually.
  • apply – same as call, but arguments are passed as an array.
  • bind – returns a new function bound to the specified this context; arguments passed in a second step.

Strings

Q54: What is a string?

A string is a data type used to store and manipulate text data, defined using quote marks.


Q55: What are template literals and string interpolation?

Template literals use backticks (`) and allow string interpolation using ${variable} syntax — the variable value is evaluated at runtime. They also support multi-line strings.


Q56: What is the difference between single quotes, double quotes, and backticks?

  • Single quotes ' and double quotes " – define normal strings; functionally identical; single quotes more popular.
  • Backticks ` – define template literals; support string interpolation and multi-line strings.

Q57: What are some important string operations in JavaScript?

  • + or concat() – concatenation
  • substring(start, end) – get a portion of a string
  • length – count characters
  • toUpperCase() / toLowerCase() – change case
  • split(separator) – split string into array
  • replace(old, new) – replace substring
  • trim() – remove leading/trailing whitespace

Q58: What is string immutability?

Strings in JavaScript are immutable — you cannot modify the contents of an existing string directly. When a string is "modified," a new memory address is allocated for the new string value. The original string remains unchanged in memory.


Q59: In how many ways can you concatenate strings?

  1. + operator: s1 + s2
  2. concat() method: s1.concat(s2)
  3. Template literals: `${s1}${s2}`
  4. join() method: [s1, s2].join(" ")

DOM

Q60: What is the DOM? What is the difference between HTML and the DOM?

The DOM (Document Object Model) represents the web page as a tree-like structure that allows JavaScript to dynamically access and manipulate the content and structure of a web page. HTML is a markup language for reading and writing; the DOM is the in-memory tree representation of that HTML that the browser uses to make pages dynamic.


Q61: How do you select, modify, create, and remove DOM elements?

  • Select: getElementById, getElementsByClassName, getElementsByTagName, querySelector, querySelectorAll
  • Modify: textContent, innerHTML, setAttribute, removeAttribute, style, classList
  • Create: createElement, cloneNode, createTextNode
  • Remove: removeChild, remove
  • Events: addEventListener, removeEventListener

Q62: What are selectors in JavaScript?

Selectors help get specific elements from the DOM based on ID, class name, or tag name. Main selectors: getElementById, getElementsByClassName, getElementsByTagName, querySelector, querySelectorAll.


Q63: What is the difference between getElementById, getElementsByClassName, and getElementsByTagName?

  • getElementById – selects a single element by its ID.
  • getElementsByClassName – selects multiple elements sharing the same class name; returns an HTMLCollection.
  • getElementsByTagName – selects multiple elements by their tag name; returns an HTMLCollection.

Q64: What is the difference between querySelector and querySelectorAll?

  • querySelector – returns the first matching element.
  • querySelectorAll – returns all matching elements as a NodeList (array-like).

Q65: What are the methods to modify elements' properties and attributes?

textContent, innerHTML, setAttribute, removeAttribute, style.setProperty, classList.add, classList.remove, classList.toggle.


Q66: What is the difference between innerHTML and textContent?

  • textContent – assigns/retrieves plain text; HTML tags are treated as literal text.
  • innerHTML – renders content as HTML; HTML tags are interpreted and applied (e.g., <strong> makes text bold).

Q67: How do you add and remove properties of HTML elements in the DOM?

  • Add: element.setAttribute("propertyName", "value")
  • Remove: element.removeAttribute("propertyName")

Q68: How do you add and remove styles from HTML elements using JavaScript?

  • element.style.setProperty("color", "blue") – add inline style.
  • element.classList.add("className") – add CSS class.
  • element.classList.remove("className") – remove CSS class.
  • element.classList.toggle("className") – add if not present, remove if present.

Q69: How do you create new elements in the DOM? What is the difference between createElement and cloneNode?

  • createElement – creates a fresh new element; set properties then appendChild to add it to the DOM.
  • cloneNode(true) – creates a copy of an existing element (with all child elements if true); then append to DOM.

Q70: What is the difference between createElement and createTextNode?

  • createElement – creates a new HTML element.
  • createTextNode – creates a text node to be appended to an existing element's content.

Error Handling

Q71: What is error handling in JavaScript?

Error handling is the process of managing errors. A try block wraps risky code; if an error occurs, it's caught by the catch block where it can be logged or handled. If no error, the catch block is skipped.


Q72: What is the role of the finally block in JavaScript?

The finally block contains code that always executes regardless of whether an error occurred or not — after either the try block (no error) or the catch block (with error). Used to ensure critical code like logging always runs.


Q73: What is the purpose of the throw statement in JavaScript?

The throw statement stops the execution of the current function and passes the error to the catch block of the calling function. Used to propagate errors from inner functions to outer functions.


Q74: What is error propagation in JavaScript?

Error propagation refers to the process of passing/propagating an error from one part of the code to another using the throw statement with try-catch blocks.


Q75: What are the best practices for error handling?

  1. Always use try-catch to handle errors appropriately.
  2. Use descriptive, readable error messages.
  3. Never leave the catch block empty (avoid "swallowing" errors).
  4. Log errors properly so developers can analyze and fix them later.

Q76: What are the different types of errors in JavaScript?

  1. SyntaxError – incorrect syntax (e.g., missing parenthesis).
  2. ReferenceError – using a variable that hasn't been declared.
  3. TypeError – using a method/operation on the wrong data type.
  4. RangeError – accessing an index or value outside the allowed range.

Objects

Q77: What are objects in JavaScript?

An object is a data type that allows you to store key-value pairs. Properties can hold strings, numbers, arrays, functions, or nested objects. Access properties using dot notation (person.name) or bracket notation (person["name"]).


Q78: In how many ways can we create an object?

  1. Object literalconst person = { name: "Happy" } (most common).
  2. Object constructorconst person = new Object(); person.name = "Happy".
  3. Object.create(parentObject) – creates a child object inheriting from a parent object.

Q79: What is the difference between an array and an object?

Array Object
Content Collection of values Collection of key-value pairs
Syntax Square brackets [] Curly braces {}
Order Elements are ordered (indexed) Properties are NOT ordered

Q80: How do you add, modify, or delete properties of an object?

  • Add/Modify: person.name = "Happy" (dot notation overrides existing or adds new).
  • Delete: delete person.name

Q81: Explain the difference between dot notation and bracket notation.

Both access object properties. Dot notation is simpler and more popular. Bracket notation is required when the property name is stored in a variable:

const key = "name";
person[key]  // works
person.key   // does NOT work

Q82: What are some common methods to iterate over the properties of an object?

  1. for...in loop – iterates keys; access values using object[key].
  2. Object.keys() + forEach – iterates keys; access values inside the loop.
  3. Object.values() + forEach – iterates values directly.

Q83: How do you check if a property exists in an object?

  1. "name" in person – returns true/false.
  2. person.hasOwnProperty("name") – returns true/false.
  3. person.name !== undefined – if not undefined, property exists.

Q84: How do you clone or copy an object?

  1. Spread syntax: const clone = { ...original } (shallow copy).
  2. Object.assign({}, original) (shallow copy).
  3. JSON.parse(JSON.stringify(original)) (deep copy — most popular).

Q85: What is the difference between deep copy and shallow copy in JavaScript?

  • Shallow copy – copies the top-level properties, but nested objects are still referenced. Modifying a nested property in the copy also modifies the original.
  • Deep copy – creates a completely independent copy including nested objects. Modifying the copy does NOT affect the original. Achieved using JSON.parse(JSON.stringify(obj)).

Q86: What is a Set object in JavaScript?

A Set is a collection of unique values — duplicates are ignored. Key methods: add(), has(), delete(), size. Use case: removing duplicates from an array by passing it to a Set constructor.


Q87: What is a Map object in JavaScript?

A Map is a collection of key-value pairs where keys can be of any data type (not just strings/symbols like regular objects). Maps also maintain insertion order of key-value pairs. Methods: get(), has(), delete(), set().


Q88: What is the difference between Map and Object in JavaScript?

Map Object
Key types Any type (string, number, function, etc.) Only strings and symbols
Order Maintains insertion order No guaranteed order
Use when Keys are of different types, order matters Simple string-keyed properties

Events

Q89: What are events? How are events triggered?

Events are actions that happen in the browser such as button clicks, mouse movements, or keyboard input. Steps: user interacts → event occurs → JavaScript function runs → web page updates. Use addEventListener(eventName, handlerFunction) to attach event handlers.


Q90: What are the types of events in JavaScript?

click, mouseover, keydown, keyup, submit, focus, blur, change, load, resize (and many more).


Q91: What is an event object in JavaScript?

Whenever any event is triggered, the browser automatically creates an event object and passes it as an argument to the event handler function. It contains properties and methods providing information about the event such as event.type (type of event) and event.target (element that triggered the event).


Q92: What is event delegation in JavaScript?

Event delegation is a technique where you attach a single event handler to a parent element to handle events on all of its child elements. JavaScript automatically handles child element events through the parent's handler. The event.target property identifies which child was clicked.


Q93: What is event bubbling in JavaScript?

Event bubbling is the process where an event triggered on a child element propagates up the DOM tree, triggering event handlers on its parent elements as well. Order: innermost element → outward to the root.


Q94: How can you stop event propagation or event bubbling?

Call event.stopPropagation() inside the event handler. This prevents the event from bubbling up to parent elements.


Q95: What is event capturing in JavaScript?

Event capturing is the opposite of event bubbling. The event is handled starting from the highest-level ancestor moving down to the target element (top to bottom). Enable it by passing true as the third parameter to addEventListener. Default is false (bubbling).


Q96: What is the purpose of event.preventDefault()?

event.preventDefault() prevents the default behavior of an event — for example, disabling a hyperlink's default navigation action on click.


Q97: What is the use of the this keyword in event handling?

Inside an event handler function, this refers to the element to which the event handler is attached.


Q98: How do you remove an event handler from an element?

Use the removeEventListener(eventName, handlerFunction) method on the element. You must pass the same event name and the same named function reference that was originally used with addEventListener.

Share:

Wednesday, 11 March 2026

React Interview Questions Answers Set 3

 

1. Which console.log will execute first in this code?

The interviewer referred to a question similar to this:

const data = false;

if (data) {
console.log("First");
}

if (new Boolean(false)) {
console.log("Second");
}

Correct Answer

Output:

Second

Explanation

new Boolean(false) creates a Boolean object, not a primitive.

Objects in JavaScript are always truthy.

Example:

Boolean(false) // false
new Boolean(false) // object (truthy)

So the condition becomes:

if (true)

Therefore:

Second

is printed.


2. Can we apply loop over object?

Yes.

Two main ways:

1. for...in

Used to iterate object keys.

const user = {
name: "Rahul",
age: 25
}

for (let key in user) {
console.log(key, user[key])
}

Output

name Rahul
age 25

2. Object.keys()

Object.keys(user).forEach(key => {
console.log(key, user[key])
})

3. Difference between forEach and for...in

forEach

Used for arrays

const arr = [1,2,3]

arr.forEach(num => console.log(num))

Features

  • Works only on arrays

  • Cannot break or continue

  • Returns undefined


for...in

Used for objects

for (let key in obj) {
console.log(key)
}

Features

  • Iterates over object keys


4. What is Single Source of Truth in Redux?

Answer

Redux keeps all application state in one central store.

Example:

Redux Store
|
|---- User State
|---- Product State
|---- Cart State

Benefits:

  • predictable state management

  • easier debugging

  • centralized state


5. What is Reconciliation in React?

Answer

Reconciliation is the process React uses to update the DOM efficiently.

Steps:

  1. React creates Virtual DOM

  2. React compares new Virtual DOM with old one

  3. Finds the difference (diffing algorithm)

  4. Updates only changed elements in Real DOM

Example:

<h1>Hello</h1>

changes to

<h1>Hello Rahul</h1>

React updates only the text node, not the entire DOM.


6. What is Diffing Algorithm?

React compares two Virtual DOM trees using O(n) diffing algorithm.

Rules:

  1. Different element types → re-render

  2. Same element type → update attributes

  3. React uses keys for list comparison

Example:

{users.map(user => (
<li key={user.id}>{user.name}</li>
))}

Keys help React identify which items changed.


7. What is React.memo?

React.memo prevents unnecessary re-rendering of components.

Example:

const Child = React.memo(({name}) => {
console.log("render")
return <h1>{name}</h1>
})

Component re-renders only if props change.


8. When should we use Context API vs Redux?

Context API

Use when:

  • small or medium app

  • few global states

  • authentication

  • theme

  • language

Example:

AuthContext
ThemeContext

Redux

Use when:

  • large applications

  • complex state

  • many components need same data

  • advanced debugging

Example:

Ecommerce
Large dashboards
Enterprise apps

9. Why does React re-render?

React re-renders when:

State changes
Props change
Parent re-renders
Context value changes

Example:

setCount(count + 1)

Triggers re-render.


10. Why should hooks not be used inside loops or conditions?

React uses hook call order to track state.

Wrong:

if (true) {
useState()
}

This breaks hook order.

Correct:

const [count, setCount] = useState(0)

Always at top level of component.

Share: