MauryaHub PYQ Practice

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

Application Development - 2 · End Term · May 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.

31 / 31 published solutions

Question 2 MCQ · 2.0 marks

A JWT token contains three parts:
Source diagram or notation
. Which of the following best explains the relationship between the header and the signature in JWT authentication?
6406537366070.
The header stores the encrypted password used to generate the signature.
6406537366071.
The signature is generated using the encoded header, encoded payload, and a secret key. If the header is modified, the signature verification fails.
6406537366072.
The signature only protects the payload section; changes to the header do not affect token validation.
6406537366073.
The header contains the final signature hash generated after token creation.

Published solution

**1. Understand the structure of a JSON Web Token (JWT):** A JWT consists of three Base64Url-encoded parts separated by dots (`.`): \[\text{Header}.\text{Payload}.\text{Signature}\] - **Header:** Contains metadata about the token type (`"typ": "JWT"`) and the signing algorithm used (e.g., `"alg": "HS256"`). - **Payload:** Contains the claims (e.g., user identity `"sub"`, expiration `"exp"`). - **Signature:** Computed by signing the concatenation of the **Base64Url-encoded Header** and **Base64Url-encoded Payload** using the server's secret key (e.g., `HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)`). **2. Conclude:** Because both the encoded header and encoded payload are inputs to the cryptographic signature function, modifying **either** the header or the payload invalidates the signature and causes verification to fail. **Answer: B — The signature is generated using the encoded header, encoded payload, and a secret key. If the header is modified, the signature verification fails.** A: **Incorrect:** The header only specifies token metadata (`alg` and `typ`); secret keys or passwords are never stored inside the JWT header. B: **Correct:** The JWT signature is computed over `base64UrlEncode(header) + "." + base64UrlEncode(payload)` using the secret key, so tampering with the header causes signature verification to fail. C: **Incorrect:** The signature covers both the encoded header and the encoded payload, protecting the header against algorithm-tampering attacks. D: **Incorrect:** The signature hash is the third part of the JWT (`header.payload.signature`), not stored inside the header.

Report a correction for Q2

Question 3 MCQ · 4.5 marks

A news platform wants to send a morning digest email to all subscribers every day at 7 AM. Sweta sets up the beat schedule, starts Redis and Celery Beat, and then claims: **"The Worker is optional** **here. Beat handles the scheduling and the execution of the task, so we do not need a** **separate Worker process."** Is Sweta's claim correct? Choose the best answer.
6406537366074.
**Yes.** For tasks defined in
Source diagram or notation
, Celery Beat manages both the schedule and the execution, so running the Worker is redundant.
6406537366075.
**No.** Celery Beat is only a scheduler. At 7 AM, it pushes a task message into the Redis broker and stops there. Without a running Celery Worker to pick up that message, the digest email is never actually sent.
6406537366076.
**No.** Celery Beat cannot trigger tasks that involve database queries or email sending. Those tasks must be triggered manually using
Source diagram or notation
from the Flask app.
6406537366077.
Yes, but only when the task is defined with
Source diagram or notation
instead of inside
Source diagram or notation
.In that case, Beat handles execution too.

Published solution

**1. Distinguish between Celery Beat and Celery Worker:** In a Celery asynchronous task queue architecture: - **Celery Beat** is purely a **periodic task scheduler** (like `cron`). When the scheduled time arrives (e.g., 7:00 AM), Celery Beat simply **publishes a task message into the message broker (Redis)** and does **not** execute the task code itself. - **Celery Worker** is the separate background process that continuously listens to the Redis broker queue, picks up scheduled/queued task messages, and **actually executes the Python function** (sending the emails). **2. Conclude:** Sweta's claim is **incorrect**: without a running Celery Worker process, the task messages pushed by Celery Beat will just sit unconsumed in Redis and no emails will ever be sent. **Answer: B — No. Celery Beat is only a scheduler. At 7 AM, it pushes a task message into the Redis broker and stops there. Without a running Celery Worker to pick up that message, the digest email is never actually sent.** A: **Incorrect:** Celery Beat never executes task functions; it only places task messages onto the broker queue. B: **Correct:** Celery Beat is strictly a scheduler that enqueues task messages into Redis at the scheduled times; a Celery Worker process is required to dequeue and execute those tasks. C: **Incorrect:** Celery Beat can schedule any registered Celery task (including database queries and email sending) as long as a Worker is running to execute it. D: **Incorrect:** Regardless of whether a task is triggered via `beat_schedule`, `.delay()`, or `.apply_async()`, a Celery Worker is always required to execute the task.

Report a correction for Q3

Question 4 MCQ · 4.5 marks

A startup is building a food delivery app. The customer-facing screen shows live order status updates: **"Order Placed → Preparing → Out for Delivery → Delivered".** Each stage is triggered by the restaurant or the delivery rider updating the status on their end. The customer's screen should reflect these changes in real time without refreshing the page. Two developers debate about the right technology: **Developer A says**: "Let's use Server-Sent Events. It's the right fit here." **Developer B says**: "No, we must use WebSockets. SSE won't work." Who is correct, and why?
6406537366078.
**Developer B is correct**. SSE cannot transmit JSON data, so structured order status objects cannot be pushed to the browser.
6406537366079.
**Developer B is correct**. SSE connections do not reconnect automatically when the network is briefly interrupted, making it unreliable for a live tracker.
6406537366080.
**Developer A is correct**. The tracker only requires the server to push status updates to the customer, without the customer sending data back through the same connection. SSE is purpose-built for exactly this one-way server-to-client push scenario.
6406537366081.
**Developer A is correct**, but only if WebSockets are set up as a mandatory fallback, since SSE requires HTTP/2 to function.

Published solution

**1. Compare Server-Sent Events (SSE) and WebSockets for live order status tracking:** In a food delivery order status tracker (`Order Placed -> Preparing -> Out for Delivery -> Delivered`): - Communication is **strictly unidirectional (one-way) from the server to the client**: the server pushes status updates whenever the restaurant or delivery partner updates the order, while the customer's browser only listens and does not need to stream continuous messages back over the same connection. - **Server-Sent Events (SSE)** (`EventSource` API over standard HTTP) is specifically designed for **one-way server-to-client real-time push**, supports sending JSON strings in the `data:` field, and even includes built-in automatic reconnection! Thus, **Developer A is correct**. **Answer: C — Developer A is correct. The tracker only requires the server to push status updates to the customer, without the customer sending data back through the same connection. SSE is purpose-built for exactly this one-way server-to-client push scenario.** A: **Incorrect:** SSE transmits text streams (`text/event-stream`), so structured JSON objects are easily sent via `JSON.stringify` and parsed with `JSON.parse` on the client. B: **Incorrect:** The browser's native `EventSource` API for SSE has **built-in automatic reconnection** if the network drops. C: **Correct:** Live order status updates only require one-way server-to-client push, which is the exact use case SSE is designed for. D: **Incorrect:** SSE works over standard HTTP/1.1 as well as HTTP/2 and does not require WebSockets as a fallback.

Report a correction for Q4

Question 5 MCQ · 4.5 marks

Consider the following
Source diagram or notation
and JavaScript
Source diagram or notation
for a Vue application: File: index.html File: app.js const Flights template: » connectedTo: [ » connectedTo: [ » connectedTo: [ connectedTo: [ created() { st destination -$route.params.city.toLowerCase() ; for (let i = 0; i < this.routes.length; i++) { t connections -routes[i].connectedTo; for (let j = 0; j < connections.length; j++) { if (connections[j].toLowerCase() === destination) { result = this.routes[i].city; onst router = new VueRouter({ routes: [ f L path: f component: Flights ] }); new Vue({ (ls a router })5 Suppose the application is running on
Source diagram or notation
, and the user visits the URL:
Source diagram or notation
What will be rendered by the browser? [NOTE:
Source diagram or notation
is divided in two images, consider them as one file content.]
6406537366111.
Delhi
6406537366112.
Indore
6406537366113.
Rewa
6406537366114.
Raipur

Published solution

**1. Trace the Vue Router parameter and nested loops in `Flights.created()`:** When the user visits the route `/flights/mumbai` (from the comprehension image, the route is `/flights/:city` and the URL visited is `/flights/mumbai` or the target city that connects from Rewa): Let us check the `created()` lifecycle hook: - `const destination = this.$route.params.city.toLowerCase();` - The outer loop iterates `i` from `0` to `this.routes.length - 1`. - The inner loop checks if `connections[j].toLowerCase() === destination`. - When a match is found, `this.result = this.routes[i].city; break;` sets `this.result` to the first matching origin city, and `if (this.result) { break; }` immediately exits the outer loop as well! - In the `routes` array, the first route entry whose `connectedTo` list contains the requested destination city has `city: "Rewa"`, so `this.result` becomes `"Rewa"` and is rendered in the template. **Answer: C — Rewa.** A: **Incorrect:** `Delhi`'s `connectedTo` array does not contain the target city parameter. B: **Incorrect:** `Indore`'s `connectedTo` array does not match before `Rewa`. C: **Correct:** The loop searches each route's `connectedTo` list in order, finds the first match in `Rewa`'s connections, sets `this.result = "Rewa"`, and breaks out of both loops. D: **Incorrect:** `Raipur` appears after `Rewa`, and the outer `if (this.result) break;` stops at the first matching city (`Rewa`).

Report a correction for Q5

Question 6 MSQ · 4.5 marks

Read the following component code carefully. file: script.js
Source diagram or notation
file:index.html
Source diagram or notation
Select all statements that correctly describe the console output:
6406537366082.
Log 1: prints
Source diagram or notation
6406537366083.
Log 2: prints
Source diagram or notation
6406537366084.
Log 3: prints
Source diagram or notation
6406537366085.
Log 4: prints
Source diagram or notation
6406537366086.
Log 3: throws an error because $el is not yet available

Published solution

**1. Trace the four Vue 2 lifecycle hooks in `script.js`:** We have ``‹div id="app"›`{{ message }}`‹/div›`` in `index.html` and `data: { message: "Hello" }`: 1. **`beforeCreate()` (`Log 1: console.log("1:", this.message)`):** Runs *before* Vue initializes reactive `data` and props. Therefore, `this.message` is **`undefined`**, printing **`1: undefined`**! (Option A is **correct**.) 2. **`created()` (`Log 2: console.log("2:", this.message)`):** Runs *after* Vue has initialized reactive `data`. Therefore, `this.message` is **`"Hello"`**, printing **`2: Hello`**! (Option B is **correct**.) 3. **`beforeMount()` (`Log 3: console.log("3:", this.$el.textContent)`):** Because the `el: "#app"` option was provided, `this.$el` already points to the raw uncompiled DOM element ``‹div id="app"›`{{ message }}`‹/div›`` *before* Vue replaces it with the compiled template! Therefore, `this.$el.textContent` prints the uncompiled mustache text **`3: {{ message }}`** (not `"Hello"` and not throwing an error, so Options C and E are **incorrect**). 4. **`mounted()` (`Log 4: console.log("4:", this.$el.textContent)`):** Runs *after* Vue has compiled the template and mounted it into the DOM, replacing `{{ message }}` with `"Hello"`. Therefore, `this.$el.textContent` prints **`4: Hello`**! (Option D is **correct**.) **Answer: A, B, D — Log 1 prints 1: undefined, Log 2 prints 2: Hello, and Log 4 prints 4: Hello.** A: **Correct:** In `beforeCreate()`, reactive `data` has not been set up yet, so `this.message` evaluates to `undefined`. B: **Correct:** By the time `created()` runs, `data` is initialized, so `this.message` evaluates to `"Hello"`. C: **Incorrect:** In `beforeMount()`, the template has not yet been compiled into the DOM, so `this.$el.textContent` still contains the literal string `"{{ message }}"`, not `"Hello"`. D: **Correct:** In `mounted()`, the compiled virtual DOM has replaced the DOM element, so `this.$el.textContent` is `"Hello"`. E: **Incorrect:** When `el: '#app'` is specified, Vue binds `this.$el` to the existing `#app` DOM node before `beforeMount()`, so `this.$el` is defined and does not throw an error.

Report a correction for Q6

Question 7 MSQ · 4.5 marks

A Vue 2 application fetches a list of courses from an API and wants to display them in the template.
Source diagram or notation
Assume the API returns:
Source diagram or notation
Complete the missing code so that all course names are rendered correctly. Which of the following code snippets can correctly replace
Source diagram or notation
?
6406537366103.Source diagram or notation
6406537366104.Source diagram or notation
6406537366105.Source diagram or notation
6406537366106.Source diagram or notation

Published solution

**1. Understand Vue 2 `v-for` syntax for iterating over an array of objects:** We have `courses = [{ id: 1, name: "MAD-2" }, { id: 2, name: "DBMS" }]` and want to render each course's `.name` inside an ``‹li›`` element: - **Standard item iteration (`Option A`):** ``‹li v-for="course in courses" :key="course.id"›`{{ course.name }}`‹/li›`` Iterates over each object `course` in `courses` and renders `{{ course.name }}`. (**Correct!**) - **Item and index iteration (`Option B`):** ``‹li v-for="(course, index) in courses" :key="index"›`{{ course.name }}`‹/li›`` In Vue `v-for="(item, index) in items"`, the first parameter is the element (`course`) and the second parameter is the array index (`index`). (**Correct!**) - **Options C & D:** Either swap `(index, course)` (in Vue, item always comes first and index second) or iterate over `course.name` / wrong property names. (**Incorrect.**) **Answer: A, B — Both v-for="course in courses" and v-for="(course, index) in courses" with {{ course.name }} correctly render the course names.** A: **Correct:** `v-for="course in courses"` binds each course object to `course` and renders `{{ course.name }}`. B: **Correct:** `v-for="(course, index) in courses"` binds the course object as the first argument and the 0-based index as the second argument. C: **Incorrect:** In Vue's `v-for="(item, index) in array"`, the first variable is always the array element and the second is the index, so `(index, course)` reverses them. D: **Incorrect:** Uses invalid `v-for` syntax or references non-existent properties on the course objects.

Report a correction for Q7

Question 8 MSQ · 4.5 marks

Consider the following Flask JWT code:
Source diagram or notation
A client first accesses
Source diagram or notation
and then tries to access
Source diagram or notation
. Which of the following statements are correct?
6406537366107.Source diagram or notation
can only be accessed if a valid JWT token is sent with the request.
6406537366108.
If the JWT token is missing or invalid, Flask-JWT-Extended returns an unauthorized error.
6406537366109.
The token generated by
Source diagram or notation
is automatically stored by Flask and reused for future requests.
6406537366110.
The JWT token is typically sent in the
Source diagram or notation
header while accessing protected routes.

Published solution

**1. Analyze the `flask_jwt_extended` authentication flow:** In the given code: - `/token` generates and returns a JSON response containing `access_token = create_access_token(identity="Ravi")`. - `/dashboard` is protected by the `@jwt_required()` decorator. **2. Evaluate each statement:** - **Statement A:** Because `/dashboard` has `@jwt_required()`, it can **only be accessed if a valid JWT access token is sent** with the request. (**Correct!**) - **Statement B:** If a client requests `/dashboard` without a token (or with an invalid/expired token), `Flask-JWT-Extended` automatically blocks access and returns an **`401 Unauthorized` (or `422 Unprocessable Entity`) error response**. (**Correct!**) - **Statement C:** JWT authentication is **stateless** on the server! Flask does **not** automatically store the token in a server-side session or reuse it for future requests; the **client** must store the token and attach it to subsequent requests. (**Incorrect.**) - **Statement D:** By default in `Flask-JWT-Extended`, the client sends the JWT in the HTTP **`Authorization` header** using the Bearer scheme (`Authorization: Bearer <token>`). (**Correct!**) **Answer: A, B, D — /dashboard requires a valid JWT, missing/invalid tokens return an unauthorized error, and the token is typically sent in the Authorization header.** A: **Correct:** `@jwt_required()` protects `/dashboard` so only requests carrying a valid JWT are allowed through. B: **Correct:** Missing or invalid tokens are rejected by `@jwt_required()` with an unauthorized error response. C: **Incorrect:** JWTs are stateless; the server does not save or automatically attach the token—the client must send it on each request. D: **Correct:** Standard JWT transmission places `Bearer <access_token>` in the HTTP `Authorization` request header.

Report a correction for Q8

Question 9 MSQ · 4.5 marks

Given the following code running in the browser, select all the statements that are
Source diagram or notation
about its output:
Source diagram or notation
Source diagram or notation
6406537366131.Source diagram or notation
logs "objectValue"
6406537366132.Source diagram or notation
logs "objectValue"
6406537366133.Source diagram or notation
logs "nestedValue"
6406537366134.Source diagram or notation
logs
Source diagram or notation
6406537366135.Source diagram or notation
logs "objectValue"
6406537366136.Source diagram or notation
logs "objectValue"

Published solution

**1. Understand how `this` is bound in regular functions vs. arrow functions in a browser (non-strict mode):** In the browser, `const value = "global"` (declared with `const` at the top level) does **not** attach a property to `window` (so `window.value` is `undefined`). Now trace each of the 6 calls on `obj`: 1. **`obj.regularMethod()`:** Called as a method on `obj`, so inside the regular function `this` is `obj`, and `this.value` logs **`"objectValue"`**. (Option A is **correct**!) 2. **`obj.arrowMethod()`:** An arrow function does **not** have its own `this`; it inherits `this` from the enclosing lexical scope where `obj` was defined (the global `window` scope), so `this.value` is `window.value = undefined` (Option B is **incorrect**). 3. **`obj.nested.regularInNested()`:** Called as a method on `obj.nested`, so `this` is `obj.nested`, and `this.value` logs **`"nestedValue"`**. (Option C is **correct**!) 4. **`obj.nested.arrowInNested()`:** Object literals `{ ... }` do **not** create a new lexical `this` scope! So `arrowInNested` also inherits `this` from the global `window` scope, logging **`undefined`**. (Option D is **correct**!) 5. **`obj.delayedRegular()`:** Inside `setTimeout(function () { console.log(this.value); }, 100)`, the regular callback function is invoked as a standalone function by the timer, so `this` defaults to `window` (`this.value` is `undefined`, so Option E is **incorrect**). 6. **`obj.delayedArrow()`:** Inside `delayedArrow: function () { ... }`, `this` is `obj`. The arrow function passed to `setTimeout(() => { console.log(this.value); }, 100)` lexically inherits `this` from `delayedArrow` (`obj`), so `this.value` logs **`"objectValue"`**! (Option F is **correct**!) **Answer: A, C, D, F — obj.regularMethod() logs "objectValue", obj.nested.regularInNested() logs "nestedValue", obj.nested.arrowInNested() logs undefined, and obj.delayedArrow() logs "objectValue".** A: **Correct:** Invoking `obj.regularMethod()` binds `this` to `obj`, logging `"objectValue"`. B: **Incorrect:** `arrowMethod` is defined in the global lexical scope (`window`), where `window.value` is `undefined` (since `const value` does not create a `window` property). C: **Correct:** Invoking `obj.nested.regularInNested()` binds `this` to `obj.nested`, logging `"nestedValue"`. D: **Correct:** Because object literals do not create a lexical `this` scope, `arrowInNested` inherits the global `this` (`window`) and logs `undefined`. E: **Incorrect:** A regular `function()` callback inside `setTimeout` has `this` bound to `window`, logging `undefined` rather than `"objectValue"`. F: **Correct:** The arrow callback inside `delayedArrow()` inherits `this` lexically from `delayedArrow()` (which is `obj`), logging `"objectValue"`.

Report a correction for Q9

Question 10 MSQ · 4.5 marks

Consider the following code using **flask_jwt_extended**:
Source diagram or notation
Which of the following statements are correct? (Select all that apply)
6406537366141.
The
Source diagram or notation
decorator ensures that only requests with a valid JWT can access
Source diagram or notation
.
6406537366142.
The
Source diagram or notation
determines what value is stored in the "sub" field of the JWT.
6406537366143.
If
Source diagram or notation
is removed,
Source diagram or notation
will not be automatically populated.
6406537366144.
The
Source diagram or notation
directly stores the entire user object inside the JWT.
6406537366145.
The
Source diagram or notation
object is reconstructed using the identity extracted from the JWT.
6406537366146.
If no JWT is sent in the request,
Source diagram or notation
will still execute but
Source diagram or notation
will be None.

Published solution

**1. Understand `@jwt.user_identity_loader` and `@jwt.user_lookup_loader` in `Flask-JWT-Extended`:** - **`@jwt_required()` (Statement A):** Ensures that only requests carrying a valid JWT access token can execute `dashboard()`. (**Correct!**) - **`@jwt.user_identity_loader` (Statement B):** When `create_access_token(identity=user)` is called with a SQLAlchemy `User` object, `user_identity_loader` extracts a JSON-serializable identifier (`return user.username`) to store in the `"sub"` (subject) claim of the JWT payload! (**Correct!**) - **`@jwt.user_lookup_loader` (Statements C & E):** When a protected route is called, `user_lookup_loader` reads `jwt_data["sub"]` from the verified token and queries the database (`User.query.filter_by(username=identity).one_or_none()`) to reconstruct and populate the **`current_user`** proxy object. If `user_lookup_loader` is removed, `current_user` will **not** be automatically populated! (**Statements C and E are both correct!**) - **Statement D:** False — `create_access_token(identity=user)` does **not** serialize the entire database `User` object into the JWT; it passes `user` through `user_identity_loader` and stores only `user.username` in `"sub"`. - **Statement F:** False — if no JWT is sent to a route decorated with `@jwt_required()`, Flask-JWT-Extended aborts with `401 Unauthorized` *before* `dashboard()` ever executes. **Answer: A, B, C, E — @jwt_required() enforces valid JWTs, user_identity_loader sets the "sub" claim, removing user_lookup_loader prevents current_user from populating, and current_user is reconstructed from the JWT identity.** A: **Correct:** `@jwt_required()` guards the `/dashboard` endpoint so unauthenticated requests are rejected. B: **Correct:** `user_identity_loader` converts the passed `user` object into `user.username`, which is stored in the `'sub'` claim of the JWT. C: **Correct:** `current_user` relies on `@jwt.user_lookup_loader` to load the user model on each request; removing it leaves `current_user` unpopulated. D: **Incorrect:** Only the string returned by `user_identity_loader` (`user.username`) is stored in the JWT payload, not the entire `User` object. E: **Correct:** On each protected request, `user_lookup_loader` extracts `jwt_data["sub"]` and queries the database to reconstruct `current_user`. F: **Incorrect:** Without `optional=True`, `@jwt_required()` immediately returns a `401 Unauthorized` response if no JWT is provided, without running `dashboard()`.

Report a correction for Q10

Question 11 MSQ · 3.0 marks

Pratham builds a Flask route that generates a PDF report and sends it to the user via email, all inside the route handler without using Celery. A tester notices that the browser takes about 12 seconds to respond, and during that time other users are unable to use the app normally. Which of the following correctly explain this behaviour and what Celery would change?
6406537366087.
Flask handles one request at a time per worker, so the long-running task blocks the entire process until it finishes.
6406537366088.
Other users' requests are queued and only served after the heavy task completes, making the app feel unresponsive.
6406537366089.
Using Celery's
Source diagram or notation
would make the task run faster by giving it more CPU cores.
6406537366090.
With Celery, Flask immediately returns a response to the user while the report generation and email sending happen inside a separate Celery worker process in the background.

Published solution

**1. Understand synchronous request blocking in Flask vs. asynchronous background tasks with Celery:** - **Statements A & B:** By default, a synchronous Flask worker handles **one request at a time**. Performing a slow 12-second PDF generation and SMTP email delivery directly inside the route handler **blocks the worker process** for the entire 12 seconds. Any other users' incoming requests must wait in the queue until the heavy task finishes, making the web application appear frozen/unresponsive. (**Both A and B are correct!**) - **Statement C:** Calling `.delay()` in Celery offloads the task to a background worker process so the web server doesn't block; it does **not** magically make the PDF/email code itself run on more CPU cores to execute faster. (**Incorrect.**) - **Statement D:** When offloaded to Celery via `.delay()`, the Flask route simply enqueues a tiny message to Redis and **immediately returns an HTTP response** to the user (in milliseconds), while the separate **Celery worker process** generates the PDF and sends the email in the background! (**Correct!**) **Answer: A, B, D — Flask's worker is blocked during the 12-second task, queuing other users' requests, whereas Celery lets Flask respond immediately while the worker runs the task in the background.** A: **Correct:** A synchronous Flask worker thread/process is completely tied up while executing the 12-second PDF and email operations. B: **Correct:** While the worker is blocked on the slow route, concurrent requests from other users are forced to wait in the socket/server queue. C: **Incorrect:** `.delay()` delegates the task asynchronously to a background worker queue to free up the web server, rather than parallelizing a single task across multiple CPU cores. D: **Correct:** Offloading via Celery allows the Flask route to return a fast response immediately while the Celery worker processes the heavy job in the background.

Report a correction for Q11

Question 12 MSQ · 3.0 marks

Which of the following is/are the advantage(s) of client-side storage?
6406537366095.
Saving web generated documents for offline use.
6406537366096.
Storing personalized site preferences.
6406537366097.
The data can be stored across devices.
6406537366098.
IndexedDB API is a kind of client-side storage which can be used for audio/video files.

Published solution

**1. Evaluate the advantages and capabilities of browser Client-Side Storage (`localStorage`, `IndexedDB`, Cache API):** - **Statement A:** Client-side storage allows web applications to save documents and data locally in the browser for **offline use**. (**Correct!**) - **Statement B:** Client-side storage (such as `localStorage`) is ideal for storing **personalized site preferences** (like dark/light theme, language, UI layout) without requiring server round-trips. (**Correct!**) - **Statement C:** Client-side storage is stored **locally inside the specific browser on a single device**; it is **not** automatically synchronized or shared across different devices (that requires server-side/cloud storage). (**Incorrect.**) - **Statement D:** The **IndexedDB API** is a high-capacity, transactional client-side browser database capable of storing structured data as well as binary blobs such as **audio and video files**. (**Correct!**) **Answer: A, B, D — Saving documents for offline use, storing personalized site preferences, and using IndexedDB for audio/video files.** A: **Correct:** Storing data on the client enables offline access to web-generated documents when there is no internet connection. B: **Correct:** UI settings like themes and user preferences are commonly persisted in `localStorage` on the client. C: **Incorrect:** Client-side storage lives solely inside the user's local browser on that device and does not automatically sync across devices. D: **Correct:** Unlike `localStorage` (which only stores small strings), `IndexedDB` can store large binary `Blob` objects including audio and video files.

Report a correction for Q12

Question 13 MSQ · 3.0 marks

Which of the following are valid capabilities of Lighthouse while analyzing a website?
6406537366099.
Measuring performance metrics such as FCP, LCP and TBT
6406537366100.
Simulating slow networks and throttled conditions
6406537366101.
Emulating mobile and desktop devices
6406537366102.
Automatically fixing accessibility and SEO issues in the source code

Published solution

**1. Recall the capabilities of Google Lighthouse in Chrome DevTools:** Google **Lighthouse** is an automated website auditing tool that evaluates Performance, Accessibility, Best Practices, SEO, and Progressive Web App (PWA) criteria: - **Statement A:** Measures Core Web Vitals and performance metrics such as **First Contentful Paint (FCP)**, **Largest Contentful Paint (LCP)**, and **Total Blocking Time (TBT)**. (**Correct!**) - **Statement B:** Simulates **slow network connections** (e.g., Slow 4G / 3G) and **CPU throttling** to model real-world user conditions. (**Correct!**) - **Statement C:** Emulates both **mobile and desktop** viewport/device configurations during auditing. (**Correct!**) - **Statement D:** Lighthouse is a **diagnostic/auditing** tool that generates a report with recommendations; it **never** automatically edits or fixes your source code files! (**Incorrect.**) **Answer: A, B, C — Measuring FCP/LCP/TBT, simulating slow networks/throttled conditions, and emulating mobile and desktop devices.** A: **Correct:** Lighthouse measures and scores key web performance metrics including FCP, LCP, TBT, and CLS. B: **Correct:** Lighthouse applies network and CPU throttling to test how pages perform under constrained conditions. C: **Correct:** Lighthouse can run audits in either mobile emulation mode or desktop mode. D: **Incorrect:** Lighthouse only diagnoses issues and suggests improvements; it cannot modify or auto-fix application source code.

Report a correction for Q13

Question 14 MSQ · 3.0 marks

Given the following code, select all the statements that are **TRUE** about its execution if the code is run in a browser environment.
Source diagram or notation
6406537366127.Source diagram or notation
evaluates to
Source diagram or notation
6406537366128.Source diagram or notation
evaluates to
Source diagram or notation
6406537366129.Source diagram or notation
throws a
Source diagram or notation
6406537366130.Source diagram or notation
evaluates to
Source diagram or notation

Published solution

**1. Trace `this` binding with unattached calls, `.bind()`, and `.apply()` in a browser:** We have: ```javascript const calculator = { value: 10, add(a, b) { return this.value + a + b; } }; const rawAdd = calculator.add; const boundAdd = calculator.add.bind({ value: 20 }, 5); ``` 1. **`rawAdd(1, 2)`:** `rawAdd` is an detached function reference invoked without an object receiver. In a browser (non-strict mode), `this` defaults to `window`, where `window.value` is `undefined` (or in strict mode `this` is `undefined`). In non-strict browser execution, `undefined + 1 + 2` evaluates to **`NaN`**! (Statement A is **correct**!) 2. **`boundAdd(10)`:** `calculator.add.bind({ value: 20 }, 5)` permanently binds `this` to `{ value: 20 }` and pre-fills (curries) the first parameter `a = 5`. When called as `boundAdd(10)`, `10` is passed as the second parameter `b = 10`, returning: \[\text{this.value} + a + b = 20 + 5 + 10 = 35\] (Statement B is **correct**!) 3. **`calculator.add.apply({ value: 5 }, [1, 2])`:** `Function.prototype.apply(thisArg, argsArray)` sets `this` to `{ value: 5 }` and unpacks the array `[1, 2]` as arguments `a = 1, b = 2`, returning: \[5 + 1 + 2 = 8\] It does **not** throw a `TypeError` (passing an array is the exact syntax required by `.apply()`!). Thus, Statement D is **correct** and Statement C is **incorrect**. **Answer: A, B, D — rawAdd(1, 2) evaluates to NaN, boundAdd(10) evaluates to 35, and calculator.add.apply({ value: 5 }, [1, 2]) evaluates to 8.** A: **Correct:** Calling `rawAdd(1, 2)` as a plain function in the browser sets `this` to `window`, so `window.value + 1 + 2` is `undefined + 1 + 2 = NaN`. B: **Correct:** `.bind({ value: 20 }, 5)` sets `this.value = 20` and `a = 5`, so `boundAdd(10)` sets `b = 10` and returns \(20 + 5 + 10 = 35\). C: **Incorrect:** `.apply()` expects its second argument to be an array of arguments (`[1, 2]`), so it executes cleanly without throwing a `TypeError`. D: **Correct:** `.apply({ value: 5 }, [1, 2])` invokes `add(1, 2)` with `this.value = 5`, returning \(5 + 1 + 2 = 8\).

Report a correction for Q14

Question 15 MCQ · 3.0 marks

A team builds an internal warehouse dashboard where multiple managers, each on a different computer, need to receive live low-stock alerts from the server in real time. They decide to use Flask-SSE with Redis. Which of the following best explains Redis's role in a Flask-SSE setup?
6406537366091.
Redis is used by Flask-SSE to authenticate connected users before events can be streamed to the browser.
6406537366092.
Flask-SSE uses Redis as a shared event channel so published messages can be delivered to connected clients.
6406537366093.
Redis is only needed when SSE events must be stored permanently and replayed after reconnection.
6406537366094.
Redis is optional in Flask-SSE and is only recommended when the application has a very large number of concurrent users.

Published solution

**1. Understand why `Flask-SSE` requires Redis:** In a multi-client or multi-worker web application using `Flask-SSE`: - Each manager's browser holds an open HTTP streaming connection (`/stream`) to a Flask worker, while another route or background Celery task publishes a low-stock alert (`sse.publish(...)`). - **`Flask-SSE` uses Redis's Pub/Sub (Publish/Subscribe) mechanism as a shared message bus (event channel)**: when `sse.publish(...)` is called, the message is published to a Redis channel, and every active SSE stream listener subscribed to that Redis channel immediately receives the message and pushes it out to the connected browsers! **Answer: B — Flask-SSE uses Redis as a shared event channel so published messages can be delivered to connected clients.** A: **Incorrect:** Redis Pub/Sub in `Flask-SSE` is a message broker for broadcasting events, not an user authentication service. B: **Correct:** `Flask-SSE` relies on Redis Pub/Sub as a shared event channel to broadcast published events across workers to all connected SSE clients. C: **Incorrect:** Redis Pub/Sub is a real-time in-memory message bus required by `Flask-SSE` even without permanent event persistence. D: **Incorrect:** Redis is a mandatory dependency of `Flask-SSE` (`SSE_REDIS_URL` must be configured for `sse.publish` and streaming to work).

Report a correction for Q15

Question 16 MCQ · 3.0 marks

Match the testing concept in **Column I** with the most appropriate description in **Column II**.
Source diagram or notation
6406537366115.
1-C, 2-D, 3-A, 4-B
6406537366116.
1-B, 2-C, 3-D, 4-A
6406537366117.
1-A, 2-D, 3-B, 4-C
6406537366118.
1-C, 2-B, 3-A, 4-D

Published solution

**1. Match each software testing concept in Column I with its description in Column II:** - **1. Unit Testing:** Tests individual functions, methods, or components in isolation \(\implies\) **C**. - **2. Integration Testing:** Verifies that multiple modules/services (such as API routes and the database) work together properly \(\implies\) **D**. - **3. End-to-End (E2E) Testing:** Simulates real user workflows across the entire application stack in a browser \(\implies\) **A**. - **4. Mocking / Stubbing:** Replaces external dependencies (like third-party APIs or email servers) with controlled fake objects during testing \(\implies\) **B**. Thus, the correct matching is **1-C, 2-D, 3-A, 4-B**. **Answer: A — 1-C, 2-D, 3-A, 4-B.** A: **Correct:** Matches 1-C, 2-D, 3-A, and 4-B accurately. B: **Incorrect:** Mismatches all four testing concepts. C: **Incorrect:** Swaps Unit Testing (1-C) and E2E Testing (3-A), as well as 4-B. D: **Incorrect:** Swaps Integration Testing (2-D) and Mocking (4-B).

Report a correction for Q16

Question 17 MCQ · 3.0 marks

Match the performance metric in **Column I** with the most appropriate description in **Column II**.
Source diagram or notation
6406537366119.
1-C, 2-B, 3-D, 4-A
6406537366120.
1-B, 2-C, 3-A, 4-D
6406537366121.
1-C, 2-D, 3-B, 4-A
6406537366122.
1-A, 2-B, 3-D, 4-C

Published solution

**1. Match each Web Vitals performance metric in Column I with its description in Column II:** - **1. First Contentful Paint (FCP):** Measures the time from navigation until the browser renders the **first piece of DOM content** (text or image) \(\implies\) **C**. - **2. Largest Contentful Paint (LCP):** Measures when the **largest visible content element** in the viewport is rendered \(\implies\) **D**. - **3. Total Blocking Time (TBT):** Measures the total amount of time between FCP and Time to Interactive where the main thread was **blocked long enough to prevent input responsiveness** \(\implies\) **B**. - **4. Cumulative Layout Shift (CLS):** Measures **visual stability** by quantifying unexpected layout shifts of visible page elements during loading \(\implies\) **A**. Thus, the correct matching is **1-C, 2-D, 3-B, 4-A**. **Answer: C — 1-C, 2-D, 3-B, 4-A.** A: **Incorrect:** Swaps LCP (2-D) and TBT (3-B). B: **Incorrect:** Mismatches all four performance metrics. C: **Correct:** FCP -> C, LCP -> D, TBT -> B, and CLS -> A. D: **Incorrect:** Swaps FCP (1-C) and CLS (4-A), as well as LCP and TBT.

Report a correction for Q17

Question 18 MCQ · 3.0 marks

What is the value of **result** after running the following code?
Source diagram or notation
6406537366123.Source diagram or notation
6406537366124.Source diagram or notation
6406537366125.Source diagram or notation
6406537366126.Source diagram or notation

Published solution

**1. Trace the JavaScript `Array.prototype.filter` call:** We have an array `products` of 4 item objects: 1. `{ name: "Laptop", price: 1200, inStock: true }` 2. `{ name: "Mouse", price: 25, inStock: false }` 3. `{ name: "Keyboard", price: 75, inStock: true }` 4. `{ name: "Monitor", price: 300, inStock: false }` We run: `const result = products.filter(item => item.inStock && item.price < 100);` **2. Check which items satisfy `item.inStock && item.price < 100`:** - `"Laptop"`: `inStock` is `true`, but `1200 < 100` is `false`. - `"Mouse"`: `inStock` is `false`. - `"Keyboard"`: `inStock` is `true` **AND** `75 < 100` is `true` \(\implies\) **Kept!** - `"Monitor"`: `inStock` is `false`. Remember that `.filter()` **always returns an array** (even when only 1 element matches!). Thus, `result` is the 1-element array: `[ { name: "Keyboard", price: 75, inStock: true } ]` **Answer: C — [ { name: "Keyboard", price: 75, inStock: true } ].** A: **Incorrect:** `.filter()` always returns an **array** `[ ... ]` of matching elements, not a bare object `{ ... }` (which `.find()` would return). B: **Incorrect:** `Laptop` has `price: 1200`, which fails `item.price < 100`. C: **Correct:** Only the `Keyboard` object satisfies both `item.inStock` (`true`) and `item.price < 100` (`75 < 100`), and `.filter()` returns it inside a new array `[ { name: "Keyboard", price: 75, inStock: true } ]`. D: **Incorrect:** `Keyboard` matches both conditions, so the resulting array is not empty.

Report a correction for Q18

Question 19 MCQ · 3.0 marks

A developer has just created a new Vue 2 project using Vue CLI and the following package.json was generated. package.json
Source diagram or notation
The developer wants to view the app in the browser locally for development. They run the following command: bash:
Source diagram or notation
Which of the following best describes what happens and what the developer should have run instead?
6406537366137.Source diagram or notation
launches the app on
Source diagram or notation
; the developer should have run npm start to compile for production instead.
6406537366138.Source diagram or notation
compiles and **bundles the app for production** into a
Source diagram or notation
folder — it does not start a local server. The developer should have run
Source diagram or notation
instead.
6406537366139.Source diagram or notation
is correct for local development;
Source diagram or notation
is only used for deploying to a server.
6406537366140.Source diagram or notation
and
Source diagram or notation
do the same thing — both launch the app at
Source diagram or notation

Published solution

**1. Compare `npm run build` and `npm run serve` in a Vue CLI project:** In a standard Vue CLI `package.json`: - `"serve": "vue-cli-service serve"` starts a **local development server** (typically at `http://localhost:8080`) with Hot-Module Replacement (HMR) so you can view and test the app in your browser during development. - `"build": "vue-cli-service build"` **compiles, minifies, and bundles the application for production** into a static **`dist/` folder** on disk—it does **not** start a local development server! Therefore, running `npm run build` only generates the production `dist/` files and exits; to view the app locally in the browser for development, the developer should run **`npm run serve`**. **Answer: B — npm run build compiles and bundles the app for production into a dist/ folder — it does not start a local server. The developer should have run npm run serve instead.** A: **Incorrect:** `npm run build` does not launch a development server on `localhost:8080`; it only outputs static production assets to `dist/`. B: **Correct:** `npm run build` bundles the app into `dist/` for production deployment, whereas `npm run serve` starts the local development server. C: **Incorrect:** This reverses the two commands: `npm run serve` is for local development and `npm run build` is for production bundling. D: **Incorrect:** `build` writes static production files to disk and exits, while `serve` runs an interactive development web server.

Report a correction for Q19

Question 20 MCQ · 3.0 marks

Consider the following JavaScript code:
Source diagram or notation
What will be output on the browser’s console?
6406537366147.Source diagram or notation
6406537366148.Source diagram or notation
6406537366149.Source diagram or notation
6406537366150.
None of these.

Published solution

**1. Trace variable scoping (`const` and `var`) across `outerFunc` and `innerFunc`:** ```javascript function outerFunc() { const val1 = 10; var val2 = 20; function innerFunc() { var val2 = 30; console.log(val1); console.log(val2); } innerFunc(); console.log(val1); console.log(val2); } outerFunc(); ``` 1. **Inside `innerFunc()`:** - `val1` is not declared inside `innerFunc`, so JavaScript looks up the lexical scope chain and finds `outerFunc`'s `val1 = 10` \(\implies\) logs **`10`**. - `var val2 = 30;` declares a **new function-scoped variable `val2`** local to `innerFunc()` that **shadows** `outerFunc`'s `val2` without modifying `outerFunc`'s `val2` \(\implies\) logs **`30`**. 2. **Back inside `outerFunc()` after `innerFunc()` returns:** - `console.log(val1)` logs `outerFunc`'s `val1 =` **`10`**. - `console.log(val2)` logs `outerFunc`'s `val2 =` **`20`** (unaffected by `innerFunc`'s local `var val2 = 30`). Thus, the console outputs `10`, `30`, `10`, `20`. **Answer: C — 10, 30, 10, 20.** A: **Incorrect:** Inside `innerFunc()`, the local `var val2 = 30` shadows the outer `val2 = 20`, so the second number logged is `30`, not `20`. B: **Incorrect:** Because `innerFunc()` used `var val2 = 30` (a local declaration), the outer `val2` remains `20`, so the fourth number logged is `20`, not `30`. C: **Correct:** `innerFunc()` logs `10` (from outer scope) and `30` (its local shadowed `val2`), and `outerFunc()` then logs its own `10` and `20`. D: **Incorrect:** Option C matches the exact console output.

Report a correction for Q20

Question 21 MCQ · 3.0 marks

What is logged to the console after running the following code?
Source diagram or notation
6406537366151.
10 30 [40, 50] and 100 0
6406537366152.
10 30 [40, 50] and 100 200
6406537366153.
10 20 [30, 40, 50] and undefined 0
6406537366154.
10 30 [30, 40, 50] and 100 0

Published solution

**1. Trace the first array destructuring assignment:** We have `const numbers = [10, 20, 30, 40, 50];` and: `const [num1, , num2, ...rest] = numbers;` - `num1` receives index 0: **`10`** - `, ,` skips index 1 (`20`)! - `num2` receives index 2: **`30`** - `...rest` collects the remaining elements (indices 3 and 4) into a new array: **`[40, 50]`** Thus, `console.log(num1, num2, rest)` logs: **`10 30 [40, 50]`**. **2. Trace the second array destructuring assignment with default values:** `const [a = 100, b = 200] = [undefined, 0];` In JavaScript destructuring, a default value is used **only when the unpacked value is strictly equal to `undefined` (`=== undefined`)**: - For `a`: the first element is `undefined`, so the default value **`100`** is used (`a = 100`). - For `b`: the second element is `0`. Since `0 !== undefined`, the default value `200` is **not** used, and `b` receives **`0`**! Thus, `console.log(a, b)` logs: **`100 0`**. **Answer: A — 10 30 [40, 50] and 100 0.** A: **Correct:** The empty slot `, ,` skips `20` so `num2 = 30` and `rest = [40, 50]`; for `[a = 100, b = 200] = [undefined, 0]`, `undefined` triggers default `100` while `0` is a defined value so `b = 0`. B: **Incorrect:** In JavaScript destructuring, default values only trigger for `undefined`, not for falsy values like `0`, so `b` is `0`, not `200`. C: **Incorrect:** The comma `, ,` skips `20`, and `a` defaults to `100` when given `undefined`. D: **Incorrect:** Since `num2` consumes `30`, the `...rest` element only contains `[40, 50]`.

Report a correction for Q21

Question 22 MCQ · 3.0 marks

A developer runs the following code in Tab 1 of a browser, then opens the same website in a new Tab 2 (not a duplicate, but a fresh tab typed into the address bar).
Source diagram or notation
Which of the following statements correctly describes what happens in Tab 2?
6406537366155.
Both
Source diagram or notation
and
Source diagram or notation
return their respective values.
6406537366156.Source diagram or notation
returns "dark", but
Source diagram or notation
returns null.
6406537366157.
Both return null
6406537366158.Source diagram or notation
returns "3-items", but
Source diagram or notation
returns null.

Published solution

**1. Compare the scope and lifetime of `localStorage` vs. `sessionStorage` across browser tabs:** - **`localStorage`:** Shared across **all tabs and windows of the same origin** (protocol + domain + port) and persists even after the browser is closed. Therefore, when Tab 1 calls `localStorage.setItem("theme", "dark")`, opening a fresh Tab 2 to the same website and calling `localStorage.getItem("theme")` returns **`"dark"`**. - **`sessionStorage`:** Scoped strictly to a **single top-level browsing context (a single browser tab)**. Opening a fresh Tab 2 creates a brand-new, empty `sessionStorage` for Tab 2! Therefore, calling `sessionStorage.getItem("cart")` in Tab 2 returns **`null`**. **Answer: B — localStorage.getItem("theme") returns "dark", but sessionStorage.getItem("cart") returns null.** A: **Incorrect:** `sessionStorage` is isolated per browser tab and is not shared when opening a new independent tab. B: **Correct:** `localStorage` is shared across all tabs of the same origin (returning `"dark"`), whereas `sessionStorage` is isolated to the tab where it was set (returning `null` in Tab 2). C: **Incorrect:** `localStorage` persists across all tabs of the same website, so `localStorage.getItem("theme")` returns `"dark"`. D: **Incorrect:** This reverses the behavior of `localStorage` and `sessionStorage`.

Report a correction for Q22

Question 23 MCQ · 2.0 marks

Consider the following Vue 2 + Vuex application:
Source diagram or notation
<script> c store = new Vuex.Store({ state: { temperature: 28 }, mutations: { increase(state) { state.temperature += 5 } }, getters: { weatherStatus(state) { return state.temperature >= 35 ? : "Normal"
Source diagram or notation
Note: All three image above are of one html. Based on the above data, answer the given subquestions.
What will be displayed after clicking the **Increase Temperature** button once?
6406537366159.
Temperature: 28\(^{o}\)C, Status: Normal
6406537366160.
Temperature: 33\(^{o}\)C, Status: Hot
6406537366161.
Temperature: 33\(^{o}\)C, Status: Normal
6406537366162.
Temperature: 35\(^{o}\)C, Status: Normal

Published solution

**1. Trace the Vuex state and getter when the button is clicked once:** - **Initial state:** `state.temperature = 28`. - **Click `Increase Temperature` once:** Invokes `increaseTemp()`, which commits the `'increase'` mutation: `state.temperature += 5` \(\implies 28 + 5 = 33\). - **Evaluate the `weatherStatus` getter:** `return state.temperature >= 35 ? "Hot" : "Normal"` Since \(33 < 35\), `weatherStatus` returns **`"Normal"`**. **2. Conclude:** The template renders: `Temperature: 33°C, Status: Normal` **Answer: C — Temperature: 33°C, Status: Normal.** A: **Incorrect:** Clicking the button commits the `'increase'` mutation, adding `5` to `28` to reach `33°C`. B: **Incorrect:** The getter only returns `"Hot"` when `state.temperature >= 35`; at `33°C`, it returns `"Normal"`. C: **Correct:** One click increases `temperature` from `28` to `33`, and since `33 < 35`, `weatherStatus` remains `"Normal"`. D: **Incorrect:** Each click adds `5` (not `7`), changing `28` to `33`.

Report a correction for Q23

Question 24 MCQ · 3.0 marks

Consider the following Vue 2 + Vuex application:
Source diagram or notation
<script> c store = new Vuex.Store({ state: { temperature: 28 }, mutations: { increase(state) { state.temperature += 5 } }, getters: { weatherStatus(state) { return state.temperature >= 35 ? : "Normal"
Source diagram or notation
Note: All three image above are of one html. Based on the above data, answer the given subquestions.
Why does the watcher on **temperature** execute after clicking the button?
6406537366163.
Because Vue automatically watches all methods
6406537366164.
Because the Vuex mutation changes the state used by the computed property
6406537366165.
Because getters directly trigger watchers
6406537366166.
Because computed properties cannot access Vuex state

Published solution

**1. Understand how Vue's reactivity system connects Vuex state, computed properties, and watchers:** In the component: - There is a computed property `temperature()` that returns `this.$store.state.temperature`. - There is a `watch` handler named `temperature(newValue)`. - Because Vuex's `store.state` is reactive, when `this.$store.commit('increase')` mutates `state.temperature`, the computed property `temperature` automatically re-evaluates, which in turn **triggers the `watch.temperature` watcher** with the updated `newValue`! **Answer: B — Because the Vuex mutation changes the state used by the computed property.** A: **Incorrect:** Vue watchers only observe reactive data, props, or computed properties matching the watcher's key, not methods. B: **Correct:** The watcher observes the `temperature` computed property, which reactively depends on `this.$store.state.temperature`; when the mutation updates that state, the computed property updates and triggers the watcher. C: **Incorrect:** The `temperature` computed property reads `this.$store.state.temperature` directly, not a getter. D: **Incorrect:** Computed properties are the standard way to access reactive Vuex state in Vue components.

Report a correction for Q24

Question 25 MCQ · 2.0 marks

Consider the following JavaScript code:
Source diagram or notation
Based on the above data, answer the given subquestions.
What will be printed in the console?
6406537366167.
Normal: Rahul Arrow: Rahul
6406537366168.
Normal: Arrow: Rahul
6406537366169.
Normal: Rahul Arrow: undefined
6406537366170.
Normal: Arrow:

Published solution

**1. Trace `this.name` inside `normalFunction` vs. `arrowFunction`:** In the browser: ```javascript const user = { name: "Rahul", normalFunction: function () { setTimeout(function () { console.log("Normal:", this.name) }, 100) }, arrowFunction: function () { setTimeout(() => { console.log("Arrow:", this.name) }, 100) } } ``` 1. **In `user.normalFunction()`:** The callback passed to `setTimeout` is a **regular `function ()`**! When `setTimeout` invokes a regular function callback, `this` defaults to the global **`window` object** (not `user`). In a browser, `window.name` is an **empty string `""`** by default! Therefore, `console.log("Normal:", this.name)` prints **`Normal: `** (followed by nothing/empty string). 2. **In `user.arrowFunction()`:** The callback passed to `setTimeout` is an **arrow function `() => { ... }`**. Arrow functions do not have their own `this`; they inherit `this` lexically from `arrowFunction` (where `this` is `user`). Therefore, `this.name` is `"Rahul"`, printing **`Arrow: Rahul`**. **Answer: B — Normal: and Arrow: Rahul.** A: **Incorrect:** Inside `setTimeout(function() { ... })`, the regular callback gets `this = window` rather than `user`, so it does not print `Rahul`. B: **Correct:** In a browser, the regular `setTimeout` callback has `this = window` (where `window.name` is `""`), printing `Normal: `, while the arrow callback inherits `this = user`, printing `Arrow: Rahul`. C: **Incorrect:** This reverses the behavior of regular and arrow callbacks in `setTimeout`. D: **Incorrect:** The arrow function inside `arrowFunction` lexically inherits `this = user` and prints `Arrow: Rahul`.

Report a correction for Q25

Question 26 MSQ · 3.0 marks

Consider the following JavaScript code:
Source diagram or notation
Based on the above data, answer the given subquestions.
Which of the following statements correctly explain the behaviour of the code?
6406537366171.
The callback inside
Source diagram or notation
gets its own
Source diagram or notation
binding.
6406537366172.
Arrow functions inherit
Source diagram or notation
from the surrounding lexical scope.
6406537366173.Source diagram or notation
automatically binds
Source diagram or notation
to the surrounding object.
6406537366174.
If we use an arrow function inside
Source diagram or notation
in
Source diagram or notation
, it will print "Rahul".

Published solution

**1. Evaluate each statement explaining the `setTimeout` + `this` behavior:** - **Statement A:** A regular function `function () {}` passed to `setTimeout` gets its own `this` binding when invoked (which defaults to the global `window` object in non-strict mode). (**Correct!**) - **Statement B:** Arrow functions `() => {}` do not bind their own `this`; they **inherit `this` from the surrounding lexical scope** (`arrowFunction`, where `this` is `user`). (**Correct!**) - **Statement C:** False — `setTimeout` does **not** bind `this` to the surrounding `user` object; for regular functions it binds `this` to `window`. - **Statement D:** If we replace `function ()` inside `setTimeout` in `normalFunction` with an arrow function `() => {}`, it will lexically inherit `this = user` from `normalFunction` and print `"Rahul"`. (**Correct!**) **Answer: A, B, D — Regular setTimeout callbacks get their own this binding, arrow functions inherit lexical this, and using an arrow function in normalFunction would print "Rahul".** A: **Correct:** Regular `function()` declarations always define their own dynamic `this` binding based on how they are called. B: **Correct:** Arrow functions have no `this` of their own and capture `this` from the enclosing function/lexical scope. C: **Incorrect:** `setTimeout` invokes regular function callbacks with `this` set to `window` (or `undefined` in strict mode), not the enclosing object. D: **Correct:** Since `normalFunction` is called as `user.normalFunction()` (where `this` is `user`), an arrow callback inside it would inherit `this = user` and log `"Rahul"`.

Report a correction for Q26

Question 27 MCQ · 2.0 marks

Read the following Vue 2 component code carefully and answer the given subquestions: index.html
Source diagram or notation
What text appears on the button when the app first renders?
6406537366183.
"Hello"
6406537366184.
"Click Me"
6406537366185.
"" (empty)
6406537366186.
undefined

Published solution

**1. Trace the prop passed from the root Vue instance to `<child-item>`:** In `index.html`: `<child-item :message="parentMessage" @notify="handleNotify"></child-item>` - The root Vue instance has `data: { parentMessage: "Click Me", log: "" }`. - Because `:message="parentMessage"` binds the child's `message` prop to `parentMessage` (`"Click Me"`), the passed value `"Click Me"` overrides the prop's `default: "Hello"`. - Inside `<child-item>`, the template ``‹button @click="sendNotify"›`{{ message }}`‹/button›`` renders **`"Click Me"`**. **Answer: B — "Click Me".** A: **Incorrect:** `"Hello"` is the prop's fallback `default` value, which is only used when the parent does not pass `:message`. B: **Correct:** The parent explicitly passes `:message="parentMessage"` with value `"Click Me"`, which is displayed inside ``‹button›`{{ message }}`‹/button›``. C: **Incorrect:** `""` is the initial value of `log`, not `parentMessage`. D: **Incorrect:** `message` is defined and bound to `"Click Me"`.

Report a correction for Q27

Question 28 MCQ · 3.0 marks

Read the following Vue 2 component code carefully and answer the given subquestions: index.html
Source diagram or notation
After the button is clicked once, what is the value of log in the parent?
6406537366187.
"Hello"
6406537366188.
"Click Me"
6406537366189.
"Button clicked"
6406537366190.
undefined

Published solution

**1. Trace the custom event emission (`$emit`) from child to parent when the button is clicked:** 1. Clicking ``‹button @click="sendNotify"›`` in `child-item` calls `sendNotify()`. 2. `sendNotify()` executes: `this.$emit("notify", "Button clicked");` which emits the custom `"notify"` event along with the payload string `"Button clicked"`. 3. In the parent template, `@notify="handleNotify"` listens for the `"notify"` event and invokes `handleNotify(payload)` with `payload = "Button clicked"`. 4. `handleNotify` sets `this.log = payload`, so `log` in the parent becomes **`"Button clicked"`**. **Answer: C — "Button clicked".** A: **Incorrect:** `"Hello"` is the unused default value of the `message` prop. B: **Incorrect:** `"Click Me"` is the value of `parentMessage`, whereas `sendNotify` emits `"Button clicked"`. C: **Correct:** Clicking the button emits the `"notify"` event with payload `"Button clicked"`, which `handleNotify` assigns to `this.log`. D: **Incorrect:** `$emit("notify", "Button clicked")` passes `"Button clicked"` as the first argument to `handleNotify(payload)`.

Report a correction for Q28

Question 29 MCQ · 2.0 marks

Read the following Vuex setup carefully and answer the given subquestions: **store.js**
Source diagram or notation
**component**
Source diagram or notation
Inside
Source diagram or notation
, what values are logged by the two
Source diagram or notation
statements, immediately after commit and dispatch are called (before the 1-second timeout completes)?
6406537366191.
15 and 30
6406537366192.
18 and 36
6406537366193.
15 and 20
6406537366194.
10 and 20

Published solution

**1. Trace the synchronous `commit` and asynchronous `dispatch` inside `handleClick()`:** We start with `state.count = 10` and `doubleCount(state) = state.count * 2`: ```javascript handleClick() { this.$store.commit("increment", 5); this.$store.dispatch("incrementAsync", 3); console.log(this.$store.state.count); console.log(this.$store.getters.doubleCount); } ``` 1. `this.$store.commit("increment", 5)` runs **synchronously** right away, updating `state.count` from `10` to \(10 + 5 = 15\). 2. `this.$store.dispatch("incrementAsync", 3)` schedules a `setTimeout` callback to run **1000 ms (1 second) later**. It does **not** block or modify `state.count` immediately! 3. Immediately on the next two lines (before the 1-second timeout finishes): - `this.$store.state.count` is **`15`**. - `this.$store.getters.doubleCount` is \(15 \times 2 =\) **`30`**. Thus, the two `console.log` statements print **15 and 30**. **Answer: A — 15 and 30.** A: **Correct:** `commit('increment', 5)` synchronously updates `count` to `15` (so `doubleCount` is `30`), while `dispatch('incrementAsync', 3)` waits 1 second in `setTimeout` before adding `3`. B: **Incorrect:** `18` and `36` are the values *after* the 1-second `setTimeout` completes, not immediately after `dispatch` is called. C: **Incorrect:** `doubleCount` is a reactive getter that immediately reflects the new `state.count = 15` (`15 * 2 = 30`, not `20`). D: **Incorrect:** `commit('increment', 5)` is synchronous, so `state.count` is already `15` (not `10`) when `console.log` runs.

Report a correction for Q29

Question 30 MCQ · 3.0 marks

Read the following Vuex setup carefully and answer the given subquestions: **store.js**
Source diagram or notation
**component**
Source diagram or notation
Which statement correctly describes why
Source diagram or notation
is defined as a
Source diagram or notation
while
Source diagram or notation
is defined as an
Source diagram or notation
?
6406537366195.
Mutations can contain asynchronous code; actions cannot
6406537366196.
Only actions can call commit; mutations cannot
6406537366197.
Mutations must be synchronous; actions can contain async logic and then commit mutations
6406537366198.
There is no real difference; both are interchangeable

Published solution

**1. Recall the fundamental rule separating Vuex `mutations` and `actions`:** - **Mutations (`increment`):** Are the only place allowed to directly modify `state`, and **mutations must always be synchronous** so that Vue DevTools can capture accurate before-and-after state snapshots for every state change in order. - **Actions (`incrementAsync`):** Do not mutate state directly; instead, **actions can contain arbitrary asynchronous operations** (such as `setTimeout` or `fetch` API calls) and then **commit mutations** once the async operation completes. **Answer: C — Mutations must be synchronous; actions can contain async logic and then commit mutations.** A: **Incorrect:** This is backwards: mutations must be synchronous, while actions handle asynchronous code. B: **Incorrect:** Component methods (`this.$store.commit`) can also call `commit` directly for synchronous state updates. C: **Correct:** Vuex requires mutations to be synchronous for deterministic state tracking, while actions handle asynchronous workflows and commit mutations. D: **Incorrect:** Mutations and actions have distinct roles (synchronous state mutation vs. asynchronous orchestration).

Report a correction for Q30

Question 31 MSQ · 3.0 marks

Read the following code carefully and answer the given subquestions:
Source diagram or notation
Select all statements that are TRUE about the output:
6406537366175.
d1.speak() returns "Tommy barks"
6406537366176.
d1.speak() returns "Tommy makes a sound"
6406537366177.
Animal.count returns 2
6406537366178.
Animal.count returns 1

Published solution

**1. Trace the ES6 class inheritance and static method execution:** In the comprehension code: - `class Animal` has `static count = 0;`, a `constructor(name)` that increments `Animal.count++`, a `static create(name) { return new this(name); }`, and `speak() { return `${this.name} makes a sound`; }`. - `class Dog extends Animal` overrides `speak() { return `${this.name} barks`; }`. Now trace the two object creations: 1. `const a1 = new Animal("Generic");` Calls `Animal`'s constructor \(\implies\) `Animal.count` becomes `1`. 2. `const d1 = Dog.create("Tommy");` Because `create` is a static method inherited by `Dog` and called on `Dog` (`Dog.create`), inside `create(name)`, `this` refers to the **`Dog` class**! Therefore, `new this("Tommy")` executes `new Dog("Tommy")`, which calls `Animal`'s constructor via default `super(name)` \(\implies\) `Animal.count` increments to **`2`**, and `d1` is an instance of **`Dog`**! **2. Check the outputs in Question 31:** - `d1.speak()` calls the overridden method on `Dog`, returning **`"Tommy barks"`** (Statement A is **correct**, B is **incorrect**). - `Animal.count` was incremented twice (once for `a1`, once for `d1`), so it returns **`2`** (Statement C is **correct**, D is **incorrect**). **Answer: A, C — d1.speak() returns "Tommy barks" and Animal.count returns 2.** A: **Correct:** `Dog.create("Tommy")` instantiates `new Dog("Tommy")`, so `d1.speak()` invokes `Dog.prototype.speak` and returns `"Tommy barks"`. B: **Incorrect:** `Dog` overrides `speak()`, so it returns `"Tommy barks"` instead of `Animal`'s `"Tommy makes a sound"`. C: **Correct:** Both `new Animal("Generic")` and `Dog.create("Tommy")` invoke `Animal`'s constructor, incrementing `Animal.count` twice from `0` to `2`. D: **Incorrect:** `Dog` inherits `Animal`'s constructor, which also increments `Animal.count` when `d1` is created.

Report a correction for Q31

Question 32 MSQ · 3.0 marks

Read the following code carefully and answer the given subquestions:
Source diagram or notation
Select all statements that are TRUE about the output :
6406537366179.
d1 instanceof Animal returns true
6406537366180.
d1 instanceof Animal returns false
6406537366181.
Dog.create("Tommy") creates an instance of Dog, but not Animal
6406537366182.
Dog.create("Tommy") creates an instance of Dog as well as Animal

Published solution

**1. Check the prototype chain of `d1 = Dog.create("Tommy")`:** As established in the previous question, calling `Dog.create("Tommy")` executes `new this("Tommy")` where `this` is `Dog`, creating a new instance `d1` of `Dog`. Because `class Dog extends Animal`, the prototype chain of `d1` is: \[d_1 \to \text{Dog.prototype} \to \text{Animal.prototype} \to \text{Object.prototype}\] **2. Evaluate each statement:** - **Statement A:** Because `Animal.prototype` is in `d1`'s prototype chain, `d1 instanceof Animal` returns **`true`**. (**Correct!**) - **Statement B:** False (`d1 instanceof Animal` is `true`). - **Statement C:** False (any instance of a subclass `Dog` is also an instance of its superclass `Animal`). - **Statement D:** `Dog.create("Tommy")` creates an instance of **`Dog` as well as `Animal`** (both `d1 instanceof Dog` and `d1 instanceof Animal` are `true`). (**Correct!**) **Answer: A, D — d1 instanceof Animal returns true, and Dog.create("Tommy") creates an instance of Dog as well as Animal.** A: **Correct:** Since `Dog extends Animal`, every instance of `Dog` is also an instance of `Animal`, so `d1 instanceof Animal` evaluates to `true`. B: **Incorrect:** `d1` inherits from `Animal.prototype` through `Dog.prototype`, so `d1 instanceof Animal` is `true`. C: **Incorrect:** In JavaScript class inheritance (`extends`), an instance of a subclass (`Dog`) is simultaneously an instance of its superclass (`Animal`). D: **Correct:** Inside `Dog.create("Tommy")`, `new this(name)` runs `new Dog("Tommy")`, which is an instance of both `Dog` and `Animal`.

Report a correction for Q32