MauryaHub PYQ Practice

Application Development - 2 · End Term · Jan 2026 · FN

Application Development - 2 · End Term · Jan 2026 FN

← Course papers · Start practice / exam

Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.

32 / 32 published solutions

Question 2 MCQ · 2.0 marks

Which of the following statements is true regarding the "this" keyword in JavaScript?
6406536934698.
"this" in an arrow function refers to the global object.
6406536934699.
"this" inside a regular function refers to the object that owns the function.
6406536934700.
Arrow functions do not have their own "this" and inherit it from the surrounding scope.
6406536934701.
"this" always points to the window object in browser environments.

Published solution

**1. Understand `this` binding in JavaScript arrow functions vs. regular functions:** Unlike regular `function` declarations (whose `this` depends on how the function is called at runtime), **arrow functions (`() => {}`) do not have their own `this` binding**. Instead, an arrow function captures `this` **lexically** from its surrounding (enclosing) scope at the time it is defined. **Answer: C — Arrow functions do not have their own "this" and inherit it from the surrounding scope.** A: **Incorrect:** An arrow function inherits `this` from its enclosing lexical scope, which is not necessarily the global object (e.g., when defined inside a method). B: **Incorrect:** In a regular function, `this` depends on the call site (and is `undefined` in strict mode or the global object when called as a standalone function). C: **Correct:** Arrow functions lack their own `this` context and lexically inherit `this` from the enclosing scope. D: **Incorrect:** Inside object methods, classes, or functions invoked with `.call()`/`.bind()`, `this` does not point to `window`.

Report a correction for Q2

Question 3 MCQ · 2.0 marks

Consider the below JavaScript program.
Source diagram or notation
What will be the output of the above program?
6406536934702.
0
6406536934703.
3
6406536934704.
6
6406536934705.
9
6406536934706.
12

Published solution

**1. Trace `Array.prototype.reduce()` on `arr = [1, 2, 3]`:** The code is: ```javascript let arr = [1, 2, 3]; let sum = arr.reduce((acc, val, idx, array) => acc + val, 0); console.log(sum); ``` - Initial accumulator value: `acc = 0`. - Iteration 1 (`val = 1`): `acc = 0 + 1 = 1`. - Iteration 2 (`val = 2`): `acc = 1 + 2 = 3`. - Iteration 3 (`val = 3`): `acc = 3 + 3 = 6`. **2. Conclude:** `console.log(sum)` outputs **`6`**. **Answer: C — 6** A: **Incorrect:** `0` is only the initial accumulator value before adding the array elements. B: **Incorrect:** `3` is the sum of the first two elements (`1 + 2`) or the sum of indices (`0 + 1 + 2`). C: **Correct:** `0 + 1 + 2 + 3 = 6`. D: **Incorrect:** The elements of `arr` are `[1, 2, 3]`, which sum to `6`, not `9`. E: **Incorrect:** The sum of `[1, 2, 3]` is `6`, not `12`.

Report a correction for Q3

Question 4 MCQ · 2.0 marks

What is the main advantage of using JWT over session-based authentication?
6406536934719.
JWTs require server-side storage for each session.
6406536934720.
JWTs are stateless and eliminate the need for server-side session storage.
6406536934721.
JWTs are longer and contain more data than session IDs.
6406536934722.
JWTs automatically handle token expiration without additional logic.

Published solution

**1. Compare session-based authentication vs. JWT (JSON Web Token) authentication:** - In **session-based authentication**, the server must store active session records in server memory or a database and look up the `session_id` on every request. - In **JWT authentication**, user identity and claims are cryptographically signed inside the token itself. The server verifies the token's signature using its secret/public key **statelessly** without needing server-side session storage. **Answer: B — JWTs are stateless and eliminate the need for server-side session storage.** A: **Incorrect:** JWTs are self-contained and do not require server-side session storage. B: **Correct:** Because a JWT carries signed claims verified via the server's secret/key, authentication is stateless and requires no server-side session table. C: **Incorrect:** Larger token size adds network header overhead and is a trade-off, not an advantage. D: **Incorrect:** Token expiration (`exp`) still requires configuring expiration claims and handling token refresh/expiry in application logic.

Report a correction for Q4

Question 5 MCQ · 2.0 marks

Which of the following HTTP methods does WebSocket use for initial handshake?
6406536934727.
GET
6406536934728.
POST
6406536934729.
PUT
6406536934730.
DELETE

Published solution

**1. Understand the WebSocket opening handshake:** To establish a WebSocket connection, the client sends a standard HTTP **`GET`** request containing upgrade headers (`Connection: Upgrade` and `Upgrade: websocket`). If the server supports WebSockets, it replies with HTTP `101 Switching Protocols`. **Answer: A — GET** A: **Correct:** RFC 6455 specifies that the WebSocket opening handshake is an HTTP `GET` request with `Upgrade: websocket` headers. B: **Incorrect:** WebSocket handshakes never use `POST`. C: **Incorrect:** `PUT` is used for resource replacement, not WebSocket protocol upgrades. D: **Incorrect:** `DELETE` is used for resource removal, not WebSocket handshakes.

Report a correction for Q5

Question 6 MCQ · 2.0 marks

You are building a cricket analytics app. The file **battingStats.js** contains the following exports:
Source diagram or notation
In another file **app.js**, which of the following import statements will correctly import both **strikeRate** and **playerName** ? ( Assume both files are in the same directory )
6406536934779.Source diagram or notation
6406536934780.Source diagram or notation
6406536934781.Source diagram or notation
6406536934782.Source diagram or notation

Published solution

**1. Identify the export type in `battingStats.js`:** Both `export const strikeRate = ...` and `export const playerName = ...` are **named exports** (not a `default` export). **2. Write the matching ES6 named `import` syntax:** In ES6 modules, named exports must be imported inside curly braces `{ ... }` from the relative path `"./battingStats.js"`: `import { strikeRate, playerName } from "./battingStats.js";` **Answer: B — `import { strikeRate, playerName } from "./battingStats.js";`** A: **Incorrect:** Omitting curly braces attempts a default import, which fails because `battingStats.js` has no `export default`. B: **Correct:** Uses curly braces `{ strikeRate, playerName }` to import the two named exports from `"./battingStats.js"`. C: **Incorrect:** `import * as stats` binds the module namespace to `stats` (`stats.strikeRate`), rather than importing the identifiers `strikeRate` and `playerName` directly. D: **Incorrect:** `require(...)` is CommonJS syntax and does not bind `strikeRate` and `playerName` in scope.

Report a correction for Q6

Question 7 MCQ · 2.0 marks

A JWT (JSON Web Token) is represented in the format:
Source diagram or notation
.In authentication using **Flask-JWT-Extended**, what does the payload part of the JWT stores?
6406536934787.
Encryption keys used to secure the token
6406536934788.
User-related data (claims) such as identity and expiration time
6406536934789.
The algorithm used for signing the token
6406536934790.
The hashed signature of the token

Published solution

**1. Recall the three parts of a JWT (`header.payload.signature`):** - **Header:** Stores metadata about the token type (`"JWT"`) and signing algorithm (e.g., `"HS256"`). - **Payload:** Stores the **claims**—user-related data such as the user's identity (`sub`), roles, creation time (`iat`), and expiration time (`exp`). - **Signature:** Stores the cryptographic signature verifying that the header and payload were not tampered with. **Answer: B — User-related data (claims) such as identity and expiration time** A: **Incorrect:** Secret signing keys are kept private on the server and are never placed inside the JWT. B: **Correct:** The middle `payload` section of a JWT contains Base64Url-encoded JSON claims such as user identity (`sub`) and expiration (`exp`). C: **Incorrect:** The signing algorithm (`alg`) is stored in the JWT **header**, not the payload. D: **Incorrect:** The cryptographic signature is the third part of the JWT (`signature`), not the `payload`.

Report a correction for Q7

Question 8 MCQ · 3.0 marks

Consider the below JavaScript program.
Source diagram or notation
What will be the output of the above program?
6406536934707.
Success!
6406536934708.
Error!
6406536934709.
Success! Error!
6406536934710.
Error! Success!

Published solution

**1. Understand Promise settlement immutability in JavaScript:** A JavaScript `Promise` can transition from `pending` to either `fulfilled` (`resolve`) or `rejected` (`reject`) **at most once**. Once `resolve('Success!')` is called on the first line of the executor, the Promise is permanently settled as **fulfilled** with value `'Success!'`, and the subsequent call to `reject('Error!')` is completely ignored. **2. Trace `.then(console.log).catch(console.log)`:** Because the promise fulfilled with `'Success!'`, the `.then(console.log)` handler runs and prints **`Success!`**, while `.catch(console.log)` is skipped. **Answer: A — Success!** A: **Correct:** Calling `resolve('Success!')` settles the Promise immediately; the subsequent `reject('Error!')` is ignored. B: **Incorrect:** `reject('Error!')` is called after the Promise has already resolved, so it has no effect. C: **Incorrect:** A Promise cannot both fulfill and reject. D: **Incorrect:** `resolve('Success!')` runs first and settles the Promise permanently.

Report a correction for Q8

Question 9 MCQ · 3.0 marks

Consider the below Vuex store configuration:
Source diagram or notation
If the addItemAsync action is dispatched with the item 'React', what will be the state of items after 2 seconds?
6406536934711.
['Angular', 'Vue']
6406536934712.
['Angular', 'Vue', 'React']
6406536934713.
['React']
6406536934714.
['Angular']

Published solution

**1. Trace the Vuex `addItemAsync` action:** 1. Initial state: `state.items` is `['Angular', 'Vue']`. 2. Dispatching `addItemAsync` with `'React'` schedules a `setTimeout` callback for `500 ms` (`0.5 seconds`). 3. At `0.5 seconds` (well before `2 seconds`), the callback runs `commit('addItem', 'React')`, which executes `state.items.push('React')`. 4. Therefore, after 2 seconds, `state.items` is **`['Angular', 'Vue', 'React']`**. **Answer: B — `['Angular', 'Vue', 'React']`** A: **Incorrect:** The `500 ms` timer completes long before 2 seconds have elapsed, so `'React'` has already been pushed. B: **Correct:** After `500 ms`, the `addItem` mutation pushes `'React'` onto the existing array `['Angular', 'Vue']`. C: **Incorrect:** `state.items.push(item)` appends `'React'` to the existing array rather than overwriting it. D: **Incorrect:** Nothing removes `'Vue'` or prevents `'React'` from being appended.

Report a correction for Q9

Question 10 MCQ · 3.0 marks

Consider the below Vue app.
Source diagram or notation
What happens when the user navigates to an undefined route like "/random"?
6406536934715.
Browser navigates to /random and shows a blank page.
6406536934716.
Browser navigates to /random but renders nothing.
6406536934717.
Browser redirects to /about and displays "About".
6406536934718.
Error: No matching route.

Published solution

**1. Inspect the `routes` array in the Vue Router configuration:** ```javascript const routes = [ { path: '/home', component: Home }, { path: '/about', component: About }, { path: '*', redirect: '/about' } ]; ``` **2. Trace navigation to `"/random"`:** `"/random"` does not match `'/home'` or `'/about'`, so it falls through to the wildcard catch-all route `{ path: '*', redirect: '/about' }`. Vue Router automatically redirects the browser to **`/about`** and renders the `About` component (``‹div›`About`‹/div›``). **Answer: C — Browser redirects to /about and displays "About".** A: **Incorrect:** The catch-all wildcard route `{ path: '*', redirect: '/about' }` redirects away from `/random`. B: **Incorrect:** Redirecting to `/about` renders the `About` component inside `<router-view>`. C: **Correct:** The wildcard route `{ path: '*', redirect: '/about' }` catches `/random`, redirects to `/about`, and renders `'About'`. D: **Incorrect:** Vue Router does not throw an uncaught error when a wildcard redirect route is defined.

Report a correction for Q10

Question 11 MCQ · 3.0 marks

What will be the output of the following JavaScript code?
Source diagram or notation
6406536934735.
number, object, false, false
6406536934736.
NaN, null, true, true
6406536934737.
number, object, true, false
6406536934738.
NaN, null, false, false

Published solution

**1. Evaluate each of the four `console.log` statements in JavaScript:** 1. `typeof NaN`: In IEEE 754 / JavaScript, `NaN` (Not-a-Number) is a special value of the numeric type, so `typeof NaN` returns **`"number"`**. 2. `typeof null`: Due to a famous historical quirk in JavaScript's original type tag implementation, `typeof null` returns **`"object"`**. 3. `NaN == null`: In JavaScript, `NaN` is **not equal to anything** (not even itself: `NaN == NaN` is `false`), so `NaN == null` evaluates to **`false`**. 4. `NaN === null`: Strict equality with `NaN` is also always **`false`**. **Answer: A — `number, object, false, false`** A: **Correct:** `typeof NaN` is `'number'`, `typeof null` is `'object'`, and both `NaN == null` and `NaN === null` are `false`. B: **Incorrect:** `typeof` never returns `'NaN'` or `'null'`, and `NaN` is never equal to `null`. C: **Incorrect:** `NaN == null` is `false`, not `true`. D: **Incorrect:** `typeof NaN` is `'number'` and `typeof null` is `'object'`.

Report a correction for Q11

Question 12 MCQ · 3.0 marks

Consider the following JavaScript program:
Source diagram or notation
What will be the output of the above program on a browser's console?
6406536934739.Source diagram or notation
6406536934740.Source diagram or notation
6406536934741.Source diagram or notation
6406536934742.Source diagram or notation

Published solution

**1. Trace each statement in the ES6 class inheritance program:** `class Dog extends Animal` constructs `const myDog = new Dog('Dog', 'Labrador');` (`this.type = 'Dog'`, `this.breed = 'Labrador'`): 1. `myDog.speak()`: Calls overridden `Dog.prototype.speak()`, printing **`Dog Labrador barks`**. 2. `console.log(myDog.getType())`: Calls inherited `Animal.prototype.getType()`, printing **`This is a Dog`**. 3. `console.log(myDog instanceof Dog)`: `myDog` is an instance of `Dog` \(\implies\) **`true`**. 4. `console.log(myDog instanceof Animal)`: `Dog` extends `Animal`, so `myDog` is also an instance of `Animal` \(\implies\) **`true`**. 5. `console.log(Dog.prototype.__proto__ === Animal.prototype)`: In ES6 class inheritance, `Dog.prototype` inherits directly from `Animal.prototype` \(\implies\) **`true`**. **Answer: A — `Dog Labrador barks`, `This is a Dog`, `true`, `true`, `true`** A: **Correct:** Overridden `speak()` logs `'Dog Labrador barks'`, inherited `getType()` logs `'This is a Dog'`, and all three prototype/instanceof checks evaluate to `true`. B: **Incorrect:** `Dog` overrides `speak()`, `getType()` uses only `${this.type}`, and `myDog instanceof Animal` is `true`. C: **Incorrect:** `getType()` returns `'This is a Dog'` (without `breed`), and `Dog.prototype.__proto__ === Animal.prototype` is `true`. D: **Incorrect:** `myDog instanceof Dog` is `true`, not `false`.

Report a correction for Q12

Question 13 MCQ · 3.0 marks

Consider the following JavaScript program:
Source diagram or notation
What will be the output of the above program?
6406536934743.Source diagram or notation
6406536934744.Source diagram or notation
6406536934745.Source diagram or notation
6406536934746.Source diagram or notation

Published solution

**1. Trace the object destructuring and spread syntax:** 1. Given `person = { firstName: 'John', lastName: 'Doe', age: 30, city: 'New York' }`. 2. `const { firstName, city, ...rest } = person;` extracts `firstName = 'John'` and `city = 'New York'`, and collects the **remaining** properties into `rest`: `rest = { lastName: 'Doe', age: 30 }` (notice `city` was already extracted, so it is **not** in `rest`). 3. `const newPerson = { firstName, location: city, ...rest };` creates: `{ firstName: 'John', location: 'New York', lastName: 'Doe', age: 30 }`. **Answer: B — Prints `'John'`, `{ lastName: 'Doe', age: 30 }`, and `{ firstName: 'John', location: 'New York', lastName: 'Doe', age: 30 }`** A: **Incorrect:** Because `city` is explicitly destructured before `...rest`, `city` is not included inside `rest` or `newPerson`. B: **Correct:** `firstName` is `'John'`, `rest` contains `{ lastName: 'Doe', age: 30 }`, and `newPerson` replaces `city` with `location: 'New York'`. C: **Incorrect:** `newPerson` does not contain a `city` key because `city` was excluded from `rest`. D: **Incorrect:** `firstName` is `'John'`, not `undefined`, and `...rest` is spread into `newPerson`.

Report a correction for Q13

Question 14 MCQ · 3.0 marks

What happens when this Flask caching code runs?
Source diagram or notation
If requests for user IDs 1, 2, 1 are made within 5 minutes, what's the total response time?
6406536934747.
15 seconds
6406536934748.
10 seconds
6406536934749.
5 seconds
6406536934750.
0 seconds

Published solution

**1. Understand `@cache.memoize(timeout=300)` in Flask-Caching:** `@cache.memoize` caches the return value of `compute_data(user_id)` keyed by the function's **arguments** (`user_id`) for `300 seconds` (5 minutes). **2. Trace the three requests (`user_id = 1, 2, 1`) within 5 minutes:** - **1st request (`user_id = 1`):** Cache **miss** \(\to\) executes `time.sleep(5)` and caches the result for `user_id = 1`. Time taken \(= 5\text{ seconds}\). - **2nd request (`user_id = 2`):** Cache **miss** (since `user_id = 2` has not been cached yet) \(\to\) executes `time.sleep(5)` and caches the result for `user_id = 2`. Time taken \(= 5\text{ seconds}\). - **3rd request (`user_id = 1`):** Cache **hit** (since `user_id = 1` was cached within the 5-minute TTL) \(\to\) returns immediately without sleeping. Time taken \(\approx 0\text{ seconds}\). **3. Sum the response times:** \[\text{Total time} = 5\text{ s} + 5\text{ s} + 0\text{ s} = 10\text{ seconds}\] **Answer: B — 10 seconds** A: **Incorrect:** `15 seconds` would occur only if caching were disabled and the second request for `user_id = 1` also slept for 5 seconds. B: **Correct:** `user_id = 1` (miss: 5s) + `user_id = 2` (miss: 5s) + `user_id = 1` (hit: 0s) = `10 seconds`. C: **Incorrect:** `user_id = 2` has a different argument from `user_id = 1`, so it is a cache miss and also takes 5 seconds. D: **Incorrect:** The cache starts empty, so the first calls for `user_id = 1` and `user_id = 2` must execute `time.sleep(5)`.

Report a correction for Q14

Question 15 MCQ · 3.0 marks

Consider the following JavaScript program:
Source diagram or notation
What will be printed in the console when the above code is executed?
6406536934775.
Passed [75,75,63]
6406536934776.
Failed [0,0,0]
6406536934777.
Failed [75,75,63]
6406536934778.
Passed [0,0,0]

Published solution

**1. Trace the `for` loop inside `allocatePeople()`:** Given `CAPACITY = 75`, `TOTAL_PEOPLE = 213`, and `slots = [0, 0, 0]` (`remaining = 213`): - **`i = 0`:** `213 >= 75` is true \(\implies\) `slots[0] = 75`, `remaining = 213 - 75 = 138`. - **`i = 1`:** `138 >= 75` is true \(\implies\) `slots[1] = 75`, `remaining = 138 - 75 = 63`. - **`i = 2`:** `63 >= 75` is false \(\implies\) `slots[2] = 63`, `remaining = 0`. So `slots` becomes `[75, 75, 63]`. **2. Trace `reject(slots)` and `try ... catch` in `startAllocation()`:** `allocatePeople()` calls **`reject(slots)`** (not `resolve(slots)`!). When `await allocatePeople()` is awaited inside `try`, the rejected Promise throws `slots` into the `catch (error)` block, which logs: `"Failed " + JSON.stringify([75, 75, 63])` \(\implies\) **`Failed [75,75,63]`**. **Answer: C — Failed [75,75,63]** A: **Incorrect:** The Promise calls `reject(slots)`, not `resolve(slots)`, so execution jumps to the `catch` block (`Failed`), not `Passed`. B: **Incorrect:** The `for` loop mutates `slots` to `[75, 75, 63]` before `reject(slots)` is called. C: **Correct:** `slots` is populated as `[75, 75, 63]` and passed to `reject(slots)`, which is caught by `catch (error)` and prints `Failed [75,75,63]`. D: **Incorrect:** `slots` is `[75, 75, 63]` and the Promise is rejected, not resolved.

Report a correction for Q15

Question 16 MCQ · 3.0 marks

Match the Vue directive in Directive with its correct functionality in Description using Vue.js.
Source diagram or notation
6406536934801.
1–A, 2–D, 3–C, 4–B
6406536934802.
1–D, 2–B, 3–C, 4–A
6406536934803.
1–B, 2–C, 3–D, 4–A
6406536934804.
1–B, 2–D, 3–C, 4–A

Published solution

**1. Match each Vue.js directive with its description:** - **1. `v-if`:** Conditionally renders (inserts/removes) elements in the DOM based on the truthiness of an expression \(\implies\) **B. Conditionally renders elements in the DOM**. - **2. `v-for`:** Loops over an array or object to render a list of items \(\implies\) **D. Renders a list of items**. - **3. `v-bind`:** Dynamically binds one or more HTML attributes (or component props) to an expression \(\implies\) **C. Binds HTML attributes dynamically**. - **4. `v-model`:** Creates a two-way data binding between form input elements and Vue component state \(\implies\) **A. Two-way data binding between input and data**. **2. Combine the matches:** **1–B, 2–D, 3–C, 4–A**. **Answer: D — 1–B, 2–D, 3–C, 4–A** A: **Incorrect:** Incorrectly matches `v-if` with two-way data binding (1–A) and `v-model` with conditional rendering (4–B). B: **Incorrect:** Incorrectly matches `v-if` with list rendering (1–D) and `v-for` with conditional rendering (2–B). C: **Incorrect:** Incorrectly matches `v-for` with attribute binding (2–C) and `v-bind` with list rendering (3–D). D: **Correct:** Matches `v-if` to conditional rendering (1–B), `v-for` to list rendering (2–D), `v-bind` to dynamic attribute binding (3–C), and `v-model` to two-way data binding (4–A).

Report a correction for Q16

Question 17 MSQ · 2.0 marks

In a Single Page Application (SPA), what are the benefits of client-side routing over server-side routing?
6406536934723.
Slower navigation between pages
6406536934724.
Reduced load on the backend server
6406536934725.
Better SEO performance by default
6406536934726.
Seamless page transitions without full reloads

Published solution

**1. Evaluate the characteristics of client-side routing in a Single Page Application (SPA):** - **Option A (`Slower navigation between pages`):** Incorrect—client-side routing updates the view in memory without re-downloading full HTML documents, making transitions faster. - **Option B (`Reduced load on the backend server`):** Correct—instead of rendering full HTML templates on every page click, the server only serves static assets once and lightweight JSON API payloads. - **Option C (`Better SEO performance by default`) vs. Option D (`Seamless page transitions without full reloads`):** Technically, client-side routing provides **seamless page transitions without full reloads (Option D)**, whereas SPAs have **poorer SEO by default** compared to server-side rendering unless SSR/prerendering is added. However, the official exam answer key recorded `['6406536934724', '6406536934725']` (Options B and C). **Answer: B, C (per official source key; see Review note for Option D)** **Review note:** In standard web architecture, the benefits of SPA client-side routing are **B** (Reduced load on the backend server) and **D** (Seamless page transitions without full reloads), whereas **C** (Better SEO performance by default) is false for client-rendered SPAs. The source answer key marked B and C (`6406536934724`, `6406536934725`); we preserve the source key and set `needs_review=true`. A: **Incorrect:** Client-side routing avoids full page reloads, making navigation faster, not slower. B: **Correct:** Offloading view rendering and route switching to the browser reduces HTML rendering load on the backend server. C: **Correct:** Marked as correct in the official source answer key (though technically client-side SPAs have worse default SEO than server-side routing without SSR; see Review note). D: **Incorrect:** Not included in the official source key (though technically seamless page transitions without full page reloads is a primary benefit of client-side routing; see Review note).

Report a correction for Q17

Question 18 MSQ · 2.0 marks

Which of the following is the correct statement?
6406536934825.
Cookie size can impact the website performance.
6406536934826.
Cookie size does not affect performance in any practical/meaningful sense.
6406536934827.
A request to static.example.com will include cookies set for example.com.
6406536934828.
A request to static.example.com will not include cookies set for example.com.

Published solution

**1. Analyze HTTP cookie domain scoping and performance:** - **Subdomain Cookie Sharing (Option C vs. D):** When a cookie is set for a parent domain `example.com` (without restricting it to a specific host), the browser automatically attaches that cookie to every HTTP request sent to any subdomain such as `static.example.com`. Thus **Option C is true** and Option D is false. - **Cookie Size Impact (Option A vs. B):** In the official source answer key, **Option B (`Cookie size does not affect performance in any practical/meaningful sense`)** and **Option C** are marked as the correct keys (`6406536934826`, `6406536934827`), even though in standard web performance engineering large cookies sent across many static asset requests can increase request header overhead. **Answer: B, C (per official source key; see Review note)** **Review note:** While Option C is unambiguously true, large cookies sent on every static asset request are a classic reason for using cookieless domains (making Option A technically true in high-traffic web performance). Because the official source key marks B and C (`6406536934826`, `6406536934827`), we preserve the source key and set `needs_review=true`. A: **Incorrect:** Not selected in the official source key (see Review note regarding cookie header overhead). B: **Correct:** Selected in the official source key (`6406536934826`). C: **Correct:** Cookies set on `example.com` (with `Domain=example.com`) are automatically included by the browser in requests to subdomains like `static.example.com`. D: **Incorrect:** Subdomains like `static.example.com` do receive cookies scoped to the parent domain `example.com`.

Report a correction for Q18

Question 19 MCQ · 4.5 marks

Consider the following Vue application with markup index.html and JavaScript file app.js.
Source diagram or notation
Suppose the application is running on http://127.0.0.1:8080. What will be rendered by the browser?
6406536934731.
Status: Initial -> Created -> Ready -> Mounted -> Done Value: 13
6406536934732.
Status: Initial -> Ready -> Mounted -> Done Value: 8
6406536934733.
Status: Initial -> Created -> Mounted -> Ready -> Done Value: 14
6406536934734.
Status: Initial -> Mounted -> Ready -> Done Value: 9

Published solution

**1. Recall the Vue 2 lifecycle hook execution order and reactivity availability:** The standard Vue 2 lifecycle hooks run in this strict chronological order (regardless of the order in which the methods are written inside the component object): 1. **`beforeCreate()`:** Runs **before** Vue initializes reactive `data` properties (`this.status` and `this.value` are `undefined`, and any assignments to `this.status` / `this.value` here are overwritten when `data` is initialized immediately afterward!). - After `data` initialization: `this.status = "Initial"`, `this.value = 10`. 2. **`created()`:** `data` is now reactive! - `this.status = "Initial" + " -> Mounted"` \(\implies\) `"Initial -> Mounted"` - `this.value = 10 * 2` \(\implies\) `20` 3. **`beforeMount()`:** Runs next before DOM mounting: - `this.status = "Initial -> Mounted" + " -> Ready"` \(\implies\) `"Initial -> Mounted -> Ready"` - `this.value = 20 - 2` \(\implies\) `18` 4. **`mounted()`:** Runs after the component is mounted to `#app`: - `this.status = "Initial -> Mounted -> Ready" + " -> Done"` \(\implies\) `"Initial -> Mounted -> Ready -> Done"` - `this.value = 18 / 2` \(\implies\) `9` **Answer: D — `Status: Initial -> Mounted -> Ready -> Done` and `Value: 9`** A: **Incorrect:** `beforeCreate()` runs before `data` is initialized, so `-> Created` and `+ 5` are overwritten by `data: { status: 'Initial', value: 10 }`, and `created()` runs before `beforeMount()`. B: **Incorrect:** `created()` (`-> Mounted`, `* 2`) executes before `beforeMount()` (`-> Ready`, `- 2`). C: **Incorrect:** `beforeCreate()` changes are overwritten when `data` is initialized, so `-> Created` does not persist. D: **Correct:** `data` initializes after `beforeCreate()`, then `created()` (`* 2 = 20`), `beforeMount()` (`- 2 = 18`), and `mounted()` (`/ 2 = 9`) run in order.

Report a correction for Q19

Question 20 MCQ · 4.5 marks

Consider the following endpoints created with a working setup of flask-security and flask- sqlalchemy.
Source diagram or notation
Three requests are made to this application: 1. GET /api/open (no authentication headers) 2. GET /api/secure (no authentication headers) 3. GET /api/superuser with valid authentication token but user has role 'basic' (not 'superuser') What will be the response status codes for these requests, respectively?
6406536934751.
200, 200, 200
6406536934752.
200, 401, 403
6406536934753.
200, 403, 401
6406536934754.
401, 403, 403

Published solution

**1. Trace each of the three requests against the Flask-Security decorators:** 1. **`GET /api/open` (no auth headers):** Has no `@auth_required` or `@roles_required` decorator \(\implies\) succeeds with HTTP **`200 OK`**. 2. **`GET /api/secure` (no auth headers):** Decorated with `@auth_required('token')`. Because no authentication token is provided, the caller is **unauthenticated** \(\implies\) returns HTTP **`401 Unauthorized`**. 3. **`GET /api/superuser` (valid token, but role `'basic'` instead of `'superuser'`):** Passes `@auth_required('token')` (authenticated), but fails `@roles_required('superuser')` (insufficient permissions / unauthorized for this resource) \(\implies\) returns HTTP **`403 Forbidden`**. **Answer: B — 200, 401, 403** A: **Incorrect:** Protected endpoints `/api/secure` and `/api/superuser` reject unauthenticated or unauthorized requests. B: **Correct:** `/api/open` returns `200`, missing authentication on `/api/secure` returns `401 Unauthorized`, and insufficient role on `/api/superuser` returns `403 Forbidden`. C: **Incorrect:** Reverses `401` (unauthenticated) and `403` (authenticated but lacking required role). D: **Incorrect:** `/api/open` requires no authentication and returns `200`.

Report a correction for Q20

Question 21 MCQ · 4.5 marks

Consider the following code snippet running in a browser. What will be the output on the console?
Source diagram or notation
6406536934755.
Ambrane 20 50 30
6406536934756.
Polycab 50 50 30
6406536934757.
Ambrane 50 50 30
6406536934758.
Ambrane 50 30 30

Published solution

**1. Analyze reference assignment vs. shallow copy vs. deep copy in `inventory()`:** Initial object: `const item = { name: "Polycab", stats: { power: 20 } };` - **`const ref1 = item;` (Reference copy):** `ref1` and `item` point to the **exact same outer object**. Setting `ref1.name = "Ambrane"` mutates `item.name` to **`"Ambrane"`**. - **`const ref2 = { ...item };` (Shallow copy):** Creates a new outer object, but `ref2.stats` and `item.stats` still point to the **exact same nested `stats` object**! Setting `ref2.stats.power = 50` mutates both `ref2.stats.power` and `item.stats.power` to **`50`**. - **`const ref3 = { name: item.name, stats: { ...item.stats } };` (Deep copy of `stats`):** Creates a brand-new `stats` object for `ref3`. Setting `ref3.stats.power = 30` changes only `ref3.stats.power` to **`30`**, leaving `item.stats.power` and `ref2.stats.power` at `50`. **2. Trace the four `console.log` outputs:** - `item.name` \(\to\) **`Ambrane`** - `item.stats.power` \(\to\) **`50`** - `ref2.stats.power` \(\to\) **`50`** - `ref3.stats.power` \(\to\) **`30`** **Answer: C — Ambrane 50 50 30** A: **Incorrect:** `ref2 = { ...item }` is a shallow copy, so `ref2.stats` shares the same reference as `item.stats`, changing `item.stats.power` to `50`. B: **Incorrect:** `ref1 = item` points to the same object as `item`, so `ref1.name = 'Ambrane'` changes `item.name` to `'Ambrane'`. C: **Correct:** `ref1` mutates `item.name` to `'Ambrane'`, `ref2` mutates the shared `stats.power` to `50` (for both `item` and `ref2`), and `ref3` mutates its own cloned `stats.power` to `30`. D: **Incorrect:** `ref2.stats` is not affected by `ref3.stats.power = 30` because `ref3` cloned `{ ...item.stats }`.

Report a correction for Q21

Question 22 MCQ · 4.5 marks

Consider the following code snippet running on a browser. What is the output on the console?
Source diagram or notation
6406536934759.
100 100 100
6406536934760.
100 undefined 100
6406536934761.
undefined undefined undefined
6406536934762.
100 undefined undefined

Published solution

**1. Trace `this` binding in each of the three calls (`func1()`, `func2()()`, `func3()`):** Given `obj = { value: 100, outerFunc: function() { const innerFunc = () => { console.log(this.value); }; return innerFunc; }, otherFunc: function() { console.log(this.value); } }`: 1. **`const func1 = obj.outerFunc(); func1();`:** Here `obj.outerFunc()` is invoked as a method on `obj`, so inside `outerFunc`, `this` is `obj`. The arrow function `innerFunc` lexically captures `this = obj`. When `func1()` is called, it logs `obj.value` = **`100`**. 2. **`const func2 = obj.outerFunc; func2()();`:** Here `func2()` is invoked as a **standalone function** (not on `obj`), so inside `outerFunc`, `this` is `window` (or `undefined`), where `this.value` is **`undefined`**. The arrow function captures that `this` and logs **`undefined`**. 3. **`const func3 = obj.otherFunc; func3();`:** Here `func3()` is also invoked as a **standalone regular function** detached from `obj`, so `this.value` is **`undefined`**. **Answer: D — 100 undefined undefined** A: **Incorrect:** Detaching regular methods `outerFunc` and `otherFunc` into standalone variables `func2` and `func3` loses the `obj` receiver binding. B: **Incorrect:** `func3()` is a regular function called without an object receiver (`obj.`), so `this.value` is `undefined`, not `100`. C: **Incorrect:** In `const func1 = obj.outerFunc()`, `outerFunc` is called directly on `obj`, so `innerFunc` lexically binds `this` to `obj` (`100`). D: **Correct:** `func1()` logs `100` (lexically captured when `obj.outerFunc()` was called on `obj`), while `func2()()` and `func3()` lose `obj` context and log `undefined`.

Report a correction for Q22

Question 23 MCQ · 4.5 marks

Consider the flask application app.py and an HTML file index.html:
Source diagram or notation
Source diagram or notation
If a user visit index.html at 10:10:10 AM, what will be logged in the console?
6406536934763.
20, 50
6406536934764.
20, 40
6406536934765.
40, 40
6406536934766.
50, 50

Published solution

**1. Trace the concurrent `fetch()` requests from `index.html` at `10:10:10 AM`:** In `test()`: - `const res1 = fetch('http://127.0.0.1:5000')` and `const res2 = fetch('http://127.0.0.1:5000/profile')` are both initiated **asynchronously and concurrently at `10:10:10 AM`** (when the current second is `10`). - Note that in Flask's development server (`app.run(debug=True)`), `threaded=True` is enabled by default, so both requests run concurrently in separate threads: - `home()` (`'/'`) sleeps for `10 seconds` from `10:10:10`, waking up at `10:10:20` and returning `datetime.now().second` = **`20`**. - `profile()` (`'/profile'`) sleeps for `30 seconds` from `10:10:10`, waking up at `10:10:40` and returning `datetime.now().second` = **`40`**. **Answer: B — 20, 40** A: **Incorrect:** `fetch()` calls are non-blocking and start concurrently at `10:10:10`, so `/profile` finishes at `10 + 30 = 40` seconds, not `20 + 30 = 50` seconds. B: **Correct:** Both requests start at `:10`; `'/'` finishes after 10s at `:20` and `'/profile'` finishes after 30s at `:40`. C: **Incorrect:** `'/'` only sleeps for 10 seconds and returns `20` immediately without waiting for `'/profile'`. D: **Incorrect:** Neither request finishes at `:50` because both start concurrently at `:10`.

Report a correction for Q23

Question 24 MCQ · 4.5 marks

A student is going on a trip and wants to check whether all essential items are packed. The application uses Vue 2 and Vuex to manage the list of packed items.The following Vue application is incomplete. Two lines of code are missing and are marked as **Line X** and **Line Y**.
Source diagram or notation
Which of the following options correctly fills **Line X** and **Line Y** so that the application works as expected?
6406536934771.Source diagram or notation
6406536934772.Source diagram or notation
6406536934773.Source diagram or notation
6406536934774.Source diagram or notation

Published solution

**1. Understand how a Vue 2 component accesses a Vuex store:** When `store` is passed into `new Vue({ el: '#app', store, ... })`, Vue injects the store instance into all components as **`this.$store`** (with a dollar sign `$`). **2. Determine Line X (`computed`) and Line Y (`methods`):** - **Line X (inside `computed`):** Define a computed getter function `packedItems()` that returns `this.$store.state.packed`: ```javascript packedItems() { return this.$store.state.packed; } ``` - **Line Y (inside `packItem(item)` method):** Trigger the synchronous Vuex mutation `ADD_ITEM` using `this.$store.commit("ADD_ITEM", item);`. **Answer: B — `packedItems() { return this.$store.state.packed; }` and `this.$store.commit("ADD_ITEM", item);`** A: **Incorrect:** Uses `this.store` instead of `this.$store` (missing the `$` prefix). B: **Correct:** Reads state via `this.$store.state.packed` inside a computed function and commits the mutation via `this.$store.commit('ADD_ITEM', item)`. C: **Incorrect:** Accesses `this.$store.packed` (missing `.state`) and calls `this.commit` instead of `this.$store.commit`. D: **Incorrect:** Assigns `this.$store.state.packed` directly instead of a computed getter function, and calls `dispatch` (which is for actions) instead of `commit` (which is for mutations).

Report a correction for Q24

Question 25 MSQ · 3.0 marks

Which of the following statement(s) is/are true about GraphQL?
6406536934767.
Mutations in GraphQL can be used to change the underlying data store.
6406536934768.
GraphQL services are created by defining types and fields of those types, then providing functions for each field.
6406536934769.
GraphQL can only fetch data from a single source.
6406536934770.
GraphQL allows only GET operations.

Published solution

**1. Evaluate each statement about GraphQL:** - **Option A (`Mutations in GraphQL can be used to change the underlying data store`):** **True.** In GraphQL, `query` operations fetch data while `mutation` operations create, update, or delete data in the underlying store. - **Option B (`GraphQL services are created by defining types and fields of those types, then providing functions for each field`):** **True.** A GraphQL service is built from a strongly typed schema (types + fields) paired with resolver functions for each field. - **Option C (`GraphQL can only fetch data from a single source`):** **False.** A single GraphQL query can aggregate data from multiple databases, microservices, and REST APIs via its resolvers. - **Option D (`GraphQL allows only GET operations`):** **False.** GraphQL over HTTP most commonly uses `POST` requests (and supports queries, mutations, and subscriptions). **Answer: A, B** A: **Correct:** GraphQL `mutation` operations are specifically designed to modify server-side data. B: **Correct:** GraphQL APIs are defined by a schema of types and fields backed by resolver functions. C: **Incorrect:** GraphQL resolvers can combine data from any number of databases and external APIs in a single query. D: **Incorrect:** GraphQL typically operates over HTTP `POST` and supports queries, mutations, and subscriptions.

Report a correction for Q25

Question 26 MSQ · 3.0 marks

Consider the following code:
Source diagram or notation
You are developing an analytics platform using Flask and Flask-JWT-Extended. A user sends a POST request to
Source diagram or notation
with:
Source diagram or notation
. Then tries to access
Source diagram or notation
. Which of the following statements are correct?
6406536934783.
The
Source diagram or notation
route will return "Welcome Jassi" only if a valid JWT token is sent in the Authorization header
6406536934784.
If no token is sent, accessing
Source diagram or notation
will result in an unauthorized error
6406536934785.
The JWT token must be sent as JSON in the request body to access
Source diagram or notation
6406536934786.
None of these

Published solution

**1. Analyze the Flask-JWT-Extended code:** - `POST /login` reads `username = request.json.get("username")` (`"Jassi"`) and returns `create_access_token(identity=username)`. - `GET /stats` is protected by `@jwt_required()`, which by default expects a valid JWT in the HTTP `Authorization: Bearer <access_token>` request header. **2. Evaluate the options:** - **Option A:** With a valid JWT for `"Jassi"` in the `Authorization` header, `get_jwt_identity()` returns `"Jassi"` and `/stats` returns `{"message": "Welcome Jassi"}`. (**Correct**) - **Option B:** If no JWT is sent when accessing `/stats`, `@jwt_required()` rejects the request with `401 Unauthorized` (`Missing Authorization Header`). (**Correct**) - **Option C:** By default, Flask-JWT-Extended looks for the token in the `Authorization` header (`headers`), not the JSON request body (especially on a `GET /stats` route). (**Incorrect**) **Answer: A, B** A: **Correct:** `@jwt_required()` validates the `Authorization: Bearer <token>` header and `get_jwt_identity()` retrieves `'Jassi'`, returning `'Welcome Jassi'`. B: **Correct:** Calling a `@jwt_required()` endpoint without a token returns an HTTP `401 Unauthorized` error. C: **Incorrect:** By default, Flask-JWT-Extended reads tokens from the `Authorization` HTTP header, not the request JSON body. D: **Incorrect:** Both Options A and B are correct.

Report a correction for Q26

Question 27 MSQ · 3.0 marks

Hamza is working on a project using **Git** and performs the following operations: 1. Creates a new branch and switches to it 2. Stages changes for commit 3. Commits changes with a message 4. Pushes the branch to a remote repository Which of the following commands are correctly used for these operations?
6406536934791.Source diagram or notation
6406536934792.Source diagram or notation
6406536934793.Source diagram or notation
6406536934794.Source diagram or notation
6406536934795.Source diagram or notation
6406536934796.Source diagram or notation

Published solution

**1. Match each of Hamza's 4 Git operations to the valid Git command:** 1. **Creates a new branch and switches to it:** `git checkout -b feature-branch` (**Option A**). 2. **Stages changes for commit:** `git add .` (**Option B**). 3. **Commits changes with a message:** `git commit -m "Initial commit"` (**Option C**). 4. **Pushes the branch to a remote repository:** `git push origin feature-branch` (**Option D**). **2. Why Options E and F are wrong:** - **Option E (`git branch feature-branch && git checkout main`):** Creates `feature-branch` but checks out `main` instead of switching to `feature-branch`. - **Option F (`git push feature-branch origin`):** Reverses the ``‹remote›` `‹branch›`` argument order of `git push`. **Answer: A, B, C, D** A: **Correct:** `git checkout -b feature-branch` creates `feature-branch` and switches to it. B: **Correct:** `git add .` stages all modified and new files in the current directory for commit. C: **Correct:** `git commit -m "Initial commit"` records a commit with the given log message. D: **Correct:** `git push origin feature-branch` pushes `feature-branch` to the `origin` remote. E: **Incorrect:** Switches to `main` instead of switching to the newly created `feature-branch`. F: **Incorrect:** `git push` expects ``‹remote›` `‹branch›`` (`origin feature-branch`), not ``‹branch›` `‹remote›``.

Report a correction for Q27

Question 28 MSQ · 3.0 marks

Prerna and Swathy are using a web application built with Vue.js for the BS Degree program. • When the page loads, the sidebar content appears instantly • However, when they click on an Assignments link, the main content takes noticeable time to load A simplified version of the component is shown below:
Source diagram or notation
Which of the following statements correctly explain why the Assignments page takes time to load?
6406536934797.
The sidebar is likely part of a parent component and is already rendered before the API call
6406536934798.
The Assignments component waits for the API response before displaying data
6406536934799.
Vue blocks rendering of all components until API calls complete
6406536934800.
The delay is caused because data is fetched asynchronously after the component is created

Published solution

**1. Analyze the Vue component lifecycle and asynchronous `fetch()` in `created()`:** In the Assignments component: - `data()` initializes `assignments: []`. - `created()` initiates an **asynchronous** `fetch("/api/assignments")` call and updates `this.assignments = data` only when the Promise resolves. **2. Evaluate the four statements:** - **Option A:** The sidebar is rendered immediately as part of the parent/layout shell without waiting for the Assignments API call. (**Correct**) - **Option B:** The Assignments component starts with an empty `assignments: []` list and must wait for the `/api/assignments` HTTP response before it has data to display. (**Correct**) - **Option C:** Vue never blocks rendering of the entire component tree while waiting for an async `fetch()` inside `created()`. (**Incorrect**) - **Option D:** Because `fetch()` runs asynchronously after component creation, there is a network delay before `this.assignments` is populated. (**Correct**) **Answer: A, B, D** A: **Correct:** The static/parent sidebar renders immediately on page load without waiting for child route API calls. B: **Correct:** `this.assignments` is initially empty (`[]`) until the `/api/assignments` response arrives. C: **Incorrect:** `fetch()` is non-blocking; Vue mounts and renders components immediately with their initial `data()` state. D: **Correct:** Fetching data asynchronously inside `created()` introduces network latency before the data is available to render.

Report a correction for Q28

Question 29 MCQ · 3.0 marks

Consider the following Vue.js application:
Source diagram or notation
Based on the above data, answer the given subquestions.
How many times will "computed run" be logged in the console during the initial render?
6406536934805.
0
6406536934806.
1
6406536934807.
Multiple times due to the loop
6406536934808.
Depends on user interaction

Published solution

**1. Trace how Vue evaluates `bigNumber` during initial render:** In the template ``‹p›`{{ bigNumber }}`‹/p›``, Vue evaluates the computed property `bigNumber()` **once** to obtain the value to display in the DOM. (Note that the `for (let i = 0; i < 10000000; i++)` loop runs *inside* that single invocation of `bigNumber()` after `console.log("computed run")` has executed once.) **2. Conclude:** During the initial render, `"computed run"` is logged in the console **1** time. **Answer: B — 1** A: **Incorrect:** Because `{{ bigNumber }}` is referenced in the template, Vue must evaluate `bigNumber()` during initial mount. B: **Correct:** Vue calls `bigNumber()` once during the initial render and caches the result, logging `'computed run'` once. C: **Incorrect:** `console.log('computed run')` is outside the `for` loop, and the `for` loop does not mutate any reactive data. D: **Incorrect:** Initial render happens automatically when `new Vue({ el: '#app' })` mounts, before any user interaction.

Report a correction for Q29

Question 30 MCQ · 3.0 marks

Consider the following Vue.js application:
Source diagram or notation
Based on the above data, answer the given subquestions.
If the
Source diagram or notation
method is modified as follows:
Source diagram or notation
What will happen when the button is clicked?
6406536934809.Source diagram or notation
will not run again
6406536934810.Source diagram or notation
will run again because a dependency changed
6406536934811.
Only time will update
6406536934812.
Vue will throw an error

Published solution

**1. Identify the reactive dependencies of `bigNumber()`:** Inside `bigNumber()`, the code reads `this.a` and `this.b` (`return s + this.a + this.b;`). Therefore, Vue tracks `this.a` and `this.b` as **reactive dependencies** of `bigNumber`. **2. Trace what happens when `calculate()` is modified to `this.a = this.a + 1;`:** When the user clicks the button, `calculate()` increments `this.a`. Because `this.a` is a reactive dependency of `bigNumber` and ``‹p›`{{ bigNumber }}`‹/p›`` is rendered in the template, Vue invalidates the cached value and **re-runs `bigNumber()`**. **Answer: B — `bigNumber()` will run again because a dependency changed** A: **Incorrect:** In the original code `calculate()` updated `this.time` (which was not a dependency of `bigNumber`), but the modified `calculate()` updates `this.a`, which *is* a dependency of `bigNumber`. B: **Correct:** Because `bigNumber` depends on `this.a`, mutating `this.a` invalidates the computed cache and triggers `bigNumber()` to re-run. C: **Incorrect:** The modified `calculate()` updates `this.a`, not `this.time`. D: **Incorrect:** Mutating a reactive data property inside a method is standard Vue usage and does not throw an error.

Report a correction for Q30

Question 31 MCQ · 3.0 marks

Consider the following Vue.js application:
Source diagram or notation
Based on the above data, answer the given subquestions.
Why is
Source diagram or notation
defined as a computed property instead of a method?
6406536934813.
Computed properties are always faster than methods
6406536934814.
Methods cannot access data properties
6406536934815.
Computed properties are cached based on their dependencies
6406536934816.
Computed properties run only once

Published solution

**1. Compare Vue `computed` properties vs. `methods`:** - A **method** invoked from a template (`{{ bigNumber() }}`) re-executes on **every single re-render** of the component, even if `this.a` and `this.b` have not changed (for example, when `this.time = Date.now()` updates!). - A **computed property** (`{{ bigNumber }}`) is **cached based on its reactive dependencies** (`this.a` and `this.b`). Unless `this.a` or `this.b` changes, Vue returns the cached result instantly without re-running the expensive `10,000,000`-iteration loop. **Answer: C — Computed properties are cached based on their dependencies** A: **Incorrect:** A single execution of a computed function is no faster than a method; the benefit comes from caching across re-renders. B: **Incorrect:** Both methods and computed properties can access reactive `data` properties via `this`. C: **Correct:** Vue caches computed properties and only re-evaluates them when one of their tracked reactive dependencies (`this.a` or `this.b`) changes. D: **Incorrect:** Computed properties re-run whenever any of their reactive dependencies change.

Report a correction for Q31

Question 32 MCQ · 4.5 marks

Consider the following Vue 2 application:
Source diagram or notation
Assume the Vue application is loaded at the url
Source diagram or notation
. The user then clicks on the Item 2 router link. Based on the above data, answer the given subquestions.
What happens **immediately after clicking "Item 2"**?
6406536934817.
The Item component is destroyed and recreated, so
Source diagram or notation
is never called
6406536934818.
The route changes, the component is reused, and
Source diagram or notation
is called
6406536934819.
The route changes, but neither watcher nor lifecycle hooks run
6406536934820.
A new Vue instance is created for the route

Published solution

**1. Understand Vue Router dynamic segment reuse (`/item/:id`):** When the user navigates from `/item/1` to `/item/2`, both URLs use the exact same route record `{ path: "/item/:id", component: Item }`. For efficiency, Vue Router **reuses the existing `Item` component instance** rather than destroying and recreating it. **2. Trace what happens on navigation to `/item/2`:** Because `$route.params.id` changes from `'1'` to `'2'` and `Item`'s template renders `{{ $route.params.id }}`, the `Item` component's DOM re-renders with the new ID `'2'`, which immediately triggers `Item`'s **`updated()`** lifecycle hook. **Answer: B — The route changes, the component is reused, and `updated()` is called** A: **Incorrect:** When transitioning between params of the same route (`/item/1` to `/item/2`), Vue Router reuses the component instance instead of destroying and recreating it. B: **Correct:** Vue Router updates `$route.params.id`, reuses the mounted `Item` component instance, re-renders its template, and fires its `updated()` hook. C: **Incorrect:** Both the root watcher on `"$route.params.id"` and `Item`'s `updated()` hook run when the parameter changes. D: **Incorrect:** Navigating between routes never creates a new root `new Vue(...)` instance.

Report a correction for Q32

Question 33 MCQ · 4.5 marks

Consider the following Vue 2 application:
Source diagram or notation
Assume the Vue application is loaded at the url
Source diagram or notation
. The user then clicks on the Item 2 router link. Based on the above data, answer the given subquestions.
Why is the
Source diagram or notation
lifecycle hook triggered in this scenario?
6406536934821.
Because Vue Router always recreates components on navigation
6406536934822.
Because lifecycle hooks run on every URL change regardless of reactivity
6406536934823.
Because router-view forces a full re-render of the component tree
6406536934824.
Because a watched route parameter updates parent reactive state, triggering a component update

Published solution

**1. Trace why the `updated()` lifecycle hook fires:** In Vue 2, the `updated()` hook is called after a reactive data/route change causes the virtual DOM to re-render and patch the real DOM: - When clicking `"Item 2"`, the route parameter `$route.params.id` changes from `'1'` to `'2'`. - The watcher `"$route.params.id"(newId)` updates the parent's reactive state `this.currentId = newId`, and the reactive `$route.params.id` binding in `Item` updates the rendered DOM without recreating the component. **Answer: D — Because a watched route parameter updates parent reactive state, triggering a component update** A: **Incorrect:** Recreating a component triggers `created()` and `mounted()`, not `updated()`; Vue Router reuses the component here. B: **Incorrect:** `updated()` only runs when reactive state affecting the rendered DOM changes, not unconditionally on every URL event. C: **Incorrect:** `<router-view>` reuses the same component instance when only dynamic route parameters (`:id`) change. D: **Correct:** Changing the watched route parameter `:id` updates reactive state and re-renders the reused component, triggering the `updated()` lifecycle hook.

Report a correction for Q33