Unit 1: Refreshing JavaScript and React Fundamentals - Subjective Questions
INT252 — Web App Development With Reactjs • Practice Questions with Detailed Answers
20 questions
Define arrow functions in JavaScript. Explain their syntax, advantages, and handling of the this keyword with suitable examples.
Arrow functions provide a concise syntax for writing JavaScript functions.
- A regular function can be written as
function add(a, b) { return a + b; }. - Its arrow-function equivalent is
const add = (a, b) => a + b;. - Parentheses may be omitted for a single parameter:
const square = n => n * n;. - An object literal must be enclosed in parentheses when returned implicitly:
const createUser = name => ({ name });.
Advantages:
- They reduce boilerplate code.
- They support implicit return for single-expression bodies.
- They are convenient for callbacks and array operations.
- They lexically inherit
thisfrom the surrounding scope.
Unlike regular functions, arrow functions do not create their own this, arguments, or prototype. Therefore, they are generally unsuitable as object methods or constructor functions. Their lexical this behavior is especially useful in React callbacks, where preserving the surrounding context may be necessary.
Distinguish between var, let, and const with reference to scope, hoisting, redeclaration, reassignment, and the temporal dead zone.
var, let, and const differ in several important ways:
- Scope:
varis function-scoped, whereasletandconstare block-scoped. - Hoisting: All three declarations are hoisted. A
varvariable is initialized withundefined, butletandconstremain inaccessible until their declaration is evaluated. - Temporal dead zone: Accessing a
letorconstvariable before its declaration produces aReferenceError. This inaccessible region is called the temporal dead zone. - Redeclaration:
varcan be redeclared in the same scope;letandconstcannot. - Reassignment: Variables declared with
varorletcan be reassigned. Aconstbinding cannot be reassigned.
A const object can still be mutated because const protects the binding rather than deeply freezing the value. For example, const user = { name: 'Asha' }; user.name = 'Riya'; is valid, while assigning a new object to user is not. In modern React code, const is preferred by default and let is used when reassignment is required.
Explain how JavaScript array methods support iteration and transformation. Compare forEach, map, filter, reduce, and find with examples relevant to React.
JavaScript array methods encourage declarative data processing:
forEach: Executes a callback for every element and normally returnsundefined. It is useful for side effects but not for producing JSX lists.map: Returns a new array by transforming every element. React commonly uses it asusers.map(user => <UserCard key={user.id} user={user} />).filter: Returns a new array containing elements that satisfy a condition, such astasks.filter(task => !task.completed).reduce: Combines all elements into one accumulated result, such asitems.reduce((total, item) => total + item.price, 0).find: Returns the first matching element orundefined, such asusers.find(user => user.id === selectedId).
These methods generally work well with React because they make transformations explicit and can produce new arrays without mutating state. map is particularly important when rendering collections, while filter and reduce are frequently used to derive display data.
Describe array and object destructuring assignments. How are default values, renamed properties, nested values, and function parameters handled through destructuring?
Destructuring extracts values from arrays or properties from objects into variables.
- Array destructuring is positional:
const [first, second] = colors;. - Elements can be skipped:
const [, second] = colors;. - Object destructuring uses property names:
const { name, age } = user;. - A property can be renamed:
const { name: userName } = user;. - A default value can be supplied:
const { role = 'guest' } = user;. - Nested properties can be extracted:
const { address: { city } } = user;. - Function parameters may be destructured directly:
function Profile({ name, age }) { ... }.
React functional components frequently destructure props to improve readability. State hooks also use array destructuring, as in const [count, setCount] = useState(0);. A default value applies only when the extracted value is undefined, not when it is null.
Compare the spread and rest operators in JavaScript. Demonstrate how each is used with arrays, objects, and function parameters.
Spread and rest use the same ... syntax, but their purposes depend on context.
Spread operator:
- Expands an iterable into individual values:
const merged = [...first, ...second];. - Copies and extends an array:
const updated = [...items, newItem];. - copies and merges enumerable object properties:
const updatedUser = { ...user, name: 'Mina' };. - Expands arguments in a call:
Math.max(...numbers).
Rest operator:
- Collects remaining function arguments:
function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); }. - Collects remaining array elements:
const [head, ...tail] = items;. - Collects remaining object properties:
const { id, ...details } = user;.
Spread expands one value into many, whereas rest gathers many values into one collection. In React, spread is useful for immutable updates and forwarding props. However, object and array spread perform only a shallow copy.
Explain ES modules and distinguish between named exports and default exports. How do modules improve the organization of a React application?
ES modules provide a standard mechanism for dividing JavaScript code into reusable files with explicit dependencies.
Named exports:
- A file may contain multiple named exports:
export const add = ...; export const subtract = ...;. - They are imported using matching names:
import { add, subtract } from './math.js';. - An import may be aliased using
as.
Default exports:
- A module can have one default export:
export default Header;. - The importer may choose its local name:
import SiteHeader from './Header.jsx';.
Modules improve React projects by:
- Separating components, hooks, services, and utilities.
- Making dependencies visible and easier to analyze.
- Preventing unnecessary global variables.
- Supporting reuse, testing, tree shaking, and code splitting.
Named exports are useful for modules exposing several related values. Default exports are commonly used when a file has one primary component, although a project should apply a consistent convention.
What is immutability? Explain why immutable state updates are important in React and show how arrays and objects can be updated without mutation.
Immutability means that an existing value is not modified after creation. Instead, an updated value is represented by a new object or array.
For an object, an immutable update can be written as const updatedUser = { ...user, name: 'Neha' };. For an array, a new item can be appended using const updatedItems = [...items, newItem];. An item can be replaced using items.map(item => item.id === id ? { ...item, done: true } : item), and removed using items.filter(item => item.id !== id).
Immutability matters in React because:
- React often uses reference comparison to detect changes.
- New references allow components and hooks to recognize updates efficiently.
- Previous state values remain reliable for debugging and undo operations.
- Pure rendering and memoization become more predictable.
- Accidental changes shared across different parts of the application are reduced.
Methods such as push, pop, splice, and direct property assignment mutate existing values. They should not be used directly on React state. The state setter should receive a newly constructed value.
Discuss the functional programming concepts that are most relevant to React, including pure functions, first-class functions, higher-order functions, composition, and avoidance of side effects.
React is strongly influenced by functional programming concepts:
- Pure functions: Given the same inputs, a pure function returns the same output and does not modify external state. A component should calculate JSX from its props and state as purely as possible.
- First-class functions: Functions can be assigned to variables, passed as arguments, and returned from other functions. React event handlers and callbacks rely on this behavior.
- Higher-order functions: Functions such as
map,filter, andreduceaccept other functions and support declarative data transformations. - Composition: Complex interfaces are constructed by combining small components. Logic can similarly be composed through utility functions and custom hooks.
- Immutability: New data structures are created instead of mutating existing state.
- Controlled side effects: Network requests, subscriptions, timers, and direct DOM operations are side effects and should be separated from render calculations, commonly through effect mechanisms.
These principles make components easier to test, reuse, and reason about. React does not require completely functional code, but predictable rendering depends on keeping side effects out of the component's render phase.
Differentiate between shallow copying and deep copying in JavaScript. Explain common copying mechanisms and their limitations.
A shallow copy creates a new top-level object or array but retains references to nested objects. For example, const copy = { ...original }; creates a new outer object, but copy.address and original.address still refer to the same nested object. Object.assign({}, original), array spread, slice(), and Array.from() also produce shallow copies.
A deep copy recursively duplicates nested mutable values so that changes in the copy do not affect the original.
Common deep-copy approaches include:
structuredClone(value), which supports many built-in data types and circular references.- Specialized libraries when custom behavior or broad compatibility is needed.
- Manual copying of only the changed nested path, which is often the best approach for React state.
- JSON serialization,
JSON.parse(JSON.stringify(value)), for limited plain data.
The JSON method loses values such as undefined, functions, and symbols, transforms dates into strings, and fails on circular references. Deep copying an entire large state object can also be expensive. React updates usually copy each level along the path that changes instead of cloning everything.
Explain referential equality in JavaScript and its role in React state comparison, dependency checking, and memoization.
For primitive values, equality compares their values. For objects, arrays, and functions, equality compares their references.
For example, const a = { value: 1 }; const b = { value: 1 }; gives a === b as false because the objects occupy different references. In contrast, const c = a; gives a === c as true.
Referential equality affects React in several ways:
- Updating state with a new object reference signals that data may have changed.
- Mutating an existing state object and reusing its reference can prevent an expected update.
- Memoized components may skip rendering when their props are shallowly equal.
- Hook dependency arrays compare dependencies by identity using
Object.issemantics. - Creating new objects or functions during every render can cause dependencies or memoized children to appear changed.
Developers should preserve references for unchanged values and create new references for changed values. Memoization tools can stabilize references where identity has a measurable effect, but they should not be applied without a reason.
Compare Single Page Applications (SPAs) and Multi Page Applications (MPAs) in terms of navigation, rendering, performance, routing, SEO, and deployment.
A Single Page Application loads an application shell and updates the visible interface through JavaScript as the user navigates. A Multi Page Application usually requests a new HTML document from the server for each page navigation.
SPA characteristics:
- Client-side routing commonly changes views without a full page reload.
- After the initial load, navigation can feel fast and preserve client state.
- More JavaScript may be downloaded initially.
- Browser history, loading states, accessibility, and SEO require deliberate handling.
- React is commonly used to build SPAs.
MPA characteristics:
- Each route can be rendered as a separate server response.
- Initial pages may require less client-side JavaScript.
- Traditional server routing and document-level navigation are straightforward.
- Full reloads can make transitions slower and reset in-memory state.
- Server-rendered HTML is naturally available to search engines.
The choice depends on interaction complexity, SEO requirements, performance constraints, team architecture, and deployment needs. Modern frameworks may combine both models through server rendering, hydration, and client-side navigation.
Explain React's philosophy and the declarative UI paradigm. Contrast declarative rendering with imperative DOM manipulation.
React follows a declarative model in which developers describe what the interface should look like for the current props and state. React then determines the DOM operations needed to produce that interface.
A declarative component might express a condition as {isLoggedIn ? <Dashboard /> : <Login />}. The developer describes the two possible UI states instead of manually finding elements, changing text, adding classes, and attaching or removing nodes.
Declarative rendering provides:
- A predictable relationship between data and interface output.
- Easier reasoning about multiple UI states.
- Automatic synchronization after state changes.
- Reusable components and compositional design.
- Less direct DOM manipulation.
In an imperative approach, the program specifies a sequence of low-level operations such as document.querySelector, createElement, and appendChild. React instead treats the UI as a function of state, often summarized conceptually as UI = f(state). Direct DOM access is still possible through refs, but it is reserved for cases such as focus management or integration with non-React libraries.
Describe component-based architecture in React. Explain component composition, props, state, reusability, and the benefits of breaking an interface into components.
Component-based architecture divides an interface into independent, reusable units called components. Each component encapsulates rendering behavior and may accept inputs called props.
- Props pass data and callbacks from a parent to a child and should be treated as read-only.
- State stores data that changes over time and affects rendering.
- Composition combines smaller components to build larger features, for example placing
Avatar,UserDetails, andActionMenuinsideUserCard. - Reusability allows the same component to render different data through props.
- Encapsulation keeps feature-specific logic and presentation close together.
A useful component should have a clear responsibility and a well-defined interface. Excessively large components are difficult to test and maintain, while splitting every small element into a separate component creates unnecessary indirection. Good boundaries generally follow reusable behavior, meaningful interface sections, and feature ownership. Composition is usually preferred over inheritance in React.
Describe the steps for setting up a React application using Vite. Explain the purpose of the main generated files and common development commands.
A React application can be created with Vite using a package-manager command such as npm create vite@latest my-app -- --template react. The usual setup process is:
- Enter the project directory with
cd my-app. - Install dependencies using
npm install. - Start the development server using
npm run dev. - Open the local URL displayed by Vite.
Important generated files include:
package.json: Defines scripts, dependencies, and project metadata.index.html: Provides the HTML entry document and root DOM container.src/main.jsx: Creates the React root and renders the top-level component.src/App.jsx: Contains the initial application component.vite.config.js: Holds optional Vite configuration.srcandpublic: Store source modules and directly served static assets respectively.
npm run build creates an optimized production bundle, while npm run preview serves that build locally for inspection. Vite provides a fast development server, module transformation, hot module replacement, and an optimized production build process.
Explain the major parts of a modern React development environment and tooling setup and state the purpose of each.
A modern React environment commonly includes:
- Node.js: Runs build tools and package-manager commands outside the browser.
- Package manager: npm, pnpm, or Yarn installs dependencies and executes scripts.
- Vite: Supplies the development server, module processing, hot module replacement, and production builds.
- Browser developer tools: Inspect the DOM, network activity, storage, performance, and JavaScript errors.
- React Developer Tools: Inspect component trees, props, state, and rendering behavior.
- ESLint: Detects suspicious code and enforces coding rules.
- Prettier: Applies consistent source formatting.
- Testing tools: Frameworks such as Vitest and React Testing Library verify behavior.
- Git: Tracks changes and supports team collaboration.
- Environment variables: Configure values that differ by environment; Vite exposes approved client variables through
import.meta.env.
Tooling should automate repeatable checks without hiding application behavior. Production builds should be tested because development mode may include additional checks and diagnostics that are absent from optimized output.
Propose and explain a feature-based folder structure for a medium-sized React application. What best practices should guide project organization?
A feature-based structure groups files by business capability instead of placing every component or utility in one global folder. One possible arrangement is:
src/app: Application setup, providers, routing, and global configuration.src/features/auth: Authentication components, hooks, API functions, and tests.src/features/products: Product-specific components, state logic, services, and tests.src/components: Truly shared UI components such as buttons and dialogs.src/hooks: Hooks shared across several features.src/liborsrc/utils: Framework adapters and general utilities.src/assets: Imported images, fonts, and other source assets.
Best practices:
- Keep files close to the feature that owns them.
- Use clear and consistent naming conventions.
- Avoid large generic folders containing unrelated files.
- Define explicit module boundaries and public exports.
- Co-locate tests and styles when that improves discoverability.
- Move code into shared directories only after genuine reuse appears.
- Prevent low-level shared modules from depending on feature-specific code.
This structure improves ownership, navigation, testing, and scalability because most changes to a feature remain localized.
Explain JSX syntax and expressions. Discuss JavaScript embedding, attributes, fragments, conditional rendering, list rendering, and important JSX restrictions.
JSX is a syntax extension that allows markup-like expressions to be written inside JavaScript. Build tools transform JSX into React element creation instructions.
Important rules and features include:
- JavaScript expressions are embedded using braces, as in
<p>{user.name}</p>. - JSX attributes commonly use camelCase, such as
onClickandtabIndex. - The HTML
classattribute is written asclassName. - Components must return one enclosing element; a fragment
<>...</>can group siblings without adding a DOM node. - Tags must be closed, for example
<img alt="Profile" />. - Conditional output can use a ternary expression or logical
&&. - Lists are commonly rendered with
mapand require stablekeyprops. - Inline styles use objects, such as
style={{ color: 'red' }}.
Statements such as if and for cannot be placed directly where JSX expects an expression. They can be evaluated before the return statement or represented through suitable expressions. JSX also escapes interpolated strings by default, reducing accidental HTML injection.
Describe how React components are rendered into the DOM. Explain the roles of index.html, the root element, createRoot, and StrictMode.
A Vite React application normally contains an element such as <div id="root"></div> in index.html. This element acts as the container managed by React.
The entry module imports createRoot from react-dom/client, locates the container, creates a React root, and renders the top-level component. Conceptually, it performs createRoot(document.getElementById('root')).render(<App />);.
The roles are:
index.html: Supplies the browser document and root container.- Root DOM element: Defines where the React-managed interface is mounted.
createRoot: Creates a modern React root connected to that container.render: Supplies the component tree that React should display.App: Usually serves as the top-level application component.StrictMode: Enables additional development checks for unsafe behavior and accidental side effects.
StrictMode does not normally render a visible DOM wrapper. In development, it may intentionally repeat certain calculations or lifecycle-related operations to expose impure code. This behavior does not occur in the same way in the production build.
Explain functional components and describe their render lifecycle from initial rendering through state or prop updates. Why must rendering remain pure?
A functional component is a JavaScript function that accepts props and returns React elements, JSX, or null. For example, function Greeting({ name }) { return <h1>Hello, {name}</h1>; } defines a component.
The broad lifecycle is:
- Trigger: Initial mounting, a state update, a parent render, or a context change requests work.
- Render phase: React calls relevant components and calculates the next element tree. This phase should remain pure and may be restarted or repeated.
- Reconciliation: React compares the new result with the previous result and determines the required changes.
- Commit phase: React applies necessary updates to the DOM and runs commit-related logic.
- Browser painting: The browser displays the updated interface.
Rendering must be pure because React may call components more than once, pause work, or abandon an intermediate render. A component should not mutate props, modify global data, start requests, or directly change the DOM during rendering. Event handlers and effect mechanisms are appropriate places for side effects.
What are the Virtual DOM and reconciliation? Explain how React compares element trees, uses keys, and updates the real DOM efficiently.
The Virtual DOM is a common term for the in-memory representation of the interface described by React elements. When props or state change, React creates a new description of the desired UI and reconciles it with the previous one.
During reconciliation:
- Elements with different types generally cause the old subtree to be replaced.
- Elements with the same type can be updated while preserving appropriate DOM nodes and component state.
- React recursively examines child elements to determine required changes.
- In lists,
keyvalues identify corresponding items across renders. - The commit phase applies the calculated changes to the real DOM.
Keys should be stable and unique among siblings. Database identifiers are usually suitable. Array indexes can cause state and rendering problems when items are inserted, removed, or reordered.
The Virtual DOM does not mean that React compares every browser DOM node blindly or that every update is automatically optimal. Its main benefit is a declarative programming model combined with a reconciliation process that batches and applies necessary DOM operations. Component design, state placement, stable keys, and sensible memoization still influence performance.
Define arrow functions in JavaScript. Explain their syntax, advantages, and handling of the this keyword with suitable examples.
Arrow functions provide a concise syntax for writing JavaScript functions.
- A regular function can be written as
function add(a, b) { return a + b; }. - Its arrow-function equivalent is
const add = (a, b) => a + b;. - Parentheses may be omitted for a single parameter:
const square = n => n * n;. - An object literal must be enclosed in parentheses when returned implicitly:
const createUser = name => ({ name });.
Advantages:
- They reduce boilerplate code.
- They support implicit return for single-expression bodies.
- They are convenient for callbacks and array operations.
- They lexically inherit
thisfrom the surrounding scope.
Unlike regular functions, arrow functions do not create their own this, arguments, or prototype. Therefore, they are generally unsuitable as object methods or constructor functions. Their lexical this behavior is especially useful in React callbacks, where preserving the surrounding context may be necessary.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →