Questions and published explanations below are available without starting a test. Some questions may not have a published solution yet.
16 / 16 published solutions
Question 2 MCQ · 2.0 marks
A developer opens the Node.js REPL and runs the following line:
Why does this fail?
6406537086580.
Node.js cannot execute JavaScript from the terminal.
6406537086581.
The Node.js runtime does not provide browser DOM APIs like
6406537086582.
works only after using
6406537086583.
V8 can execute only arithmetic expressions, not DOM code.
Published solution
**1. Separate the language from its environment:** Node.js runs JavaScript using the V8 engine, but browser facilities are additional APIs supplied by a web browser.
**2. Inspect the expression:** document.querySelector("h1") tries to access the browser's document object, which represents the HTML page. A normal Node.js REPL has no document global and no page DOM.
**3. Explain the failure:** The expression therefore raises a ReferenceError for document. It would work in a browser with a document, or with an explicitly supplied DOM implementation; delaying the same expression does not create a DOM.
**Answer: B.**
A: **Incorrect:** The Node REPL is specifically designed to execute JavaScript from a terminal.
B: **Correct:** A standard Node runtime does not supply the browser document object.
C: **Incorrect:** A timer changes when code runs; it does not provide missing DOM APIs.
D: **Incorrect:** V8 supports the JavaScript language generally; the missing facility belongs to the host environment.
The above code is initially loaded on the browser and then the browser is refreshed two times.
What will be the final output?
6406537086612.
['Tablet', 'Tablet']
6406537086613.
['Tablet', 'Tablet', 'Tablet']
6406537086614.
[{ id: 3, name: 'Tablet' }]
6406537086615.
[undefined]
Published solution
**1. Read the value being added:** The argument is {id:3,name:'Tablet'}.name, so addProduct receives the string 'Tablet', not the entire product object.
**2. Trace storage:** addProduct reads the existing products array, appends that string, and writes the JSON array to localStorage. getProducts reads and parses the stored array.
**3. Count executions:** Starting with no saved products, the initial load stores one 'Tablet'. The first refresh appends a second, and the second refresh appends a third. localStorage survives refreshes, so the final array is ['Tablet','Tablet','Tablet'].
**Assumption:** This result uses the question's intended initially empty products storage. Pre-existing values would also remain in the array.
**Answer: B.**
A: **Incorrect:** This counts only two executions, ignoring the initial load.
B: **Correct:** There are three executions: the initial load and two refreshes.
C: **Incorrect:** The .name expression passes a string rather than a complete object.
D: **Incorrect:** The object has a name property, so the passed value is not undefined.
Point out the error with the following code that is used to display user data?
6406537086620.
should use POST method by default, not GET
6406537086621.
and
will throw errors because response is a
6406537086622.
cannot be called on a
response; use
instead
6406537086623.
does not work inside
functions
Published solution
**1. Identify fetch's return value:** fetch returns a Promise. Declaring getUser as async does not automatically await every expression inside it. The assignment needs const response = await fetch(...).
**2. Trace the actual code:** Without await, response.ok is undefined because response is still a Promise. Reading that missing property does not itself throw; !response.ok is true, so the program immediately throws its own Error('Request failed'). The response.json() line is therefore not reached in this execution.
**3. Explain the intended error:** A Promise also has no Response.json method. Once fetch has been awaited, check response.ok and then await response.json(). Option B identifies the missing await/Promise mistake, although its claim that both expressions directly throw is imprecise.
**Answer: B.**
A: **Incorrect:** GET is the default method and is appropriate for reading user data.
B: **Correct:** This is the intended choice because the Response has not been awaited; the precise immediate failure is explained above.
C: **Incorrect:** A resolved fetch Response can be parsed with json when its body is JSON.
D: **Incorrect:** fetch is commonly used inside async functions.
What is the correct output order for the following code?
6406537086584.
A
B
C
D
6406537086585.
C
A
D
B
6406537086586.
A
D
C
B
6406537086587.
A
D
B
C
Published solution
**1. Run synchronous statements:** console.log('A') runs immediately. setTimeout schedules B for a future task; it does not interrupt the current script. The Promise handler for C is queued as a microtask. console.log('D') then runs immediately.
**2. Drain microtasks:** After the current script finishes, the Promise callback prints C before the event loop starts the queued timer task.
**3. Run the timer:** B prints last, even with a zero-millisecond delay. Therefore the order is A, D, C, B.
**Answer: C.**
A: **Incorrect:** The timer cannot interrupt synchronous execution to print B second.
B: **Incorrect:** C is asynchronous, so it cannot print before the first synchronous A.
C: **Correct:** Synchronous A and D run first, then Promise microtask C, then timer task B.
D: **Incorrect:** The Promise microtask C runs before the timer B.
because the nested object is still shared in a shallow copy.
6406537086594.
It becomes
because
is removed from the original object.
6406537086595.
The code throws an error because nested objects cannot be copied with
spread syntax.
Published solution
**1. Understand spread copying:** const copy={...settings} creates a new outer object. Primitive properties are copied by value, but nested objects are copied as references.
**2. Follow the shared reference:** Both settings.layout and copy.layout point to the same layout object. Changing copy.layout.sidebar therefore changes that shared object's sidebar property.
**3. Read the original:** settings.layout.sidebar becomes false. To modify a nested object independently, copy that nested level as well, or use a suitable deep-cloning method.
**Answer: B.**
A: **Incorrect:** Object spread is shallow; it does not recursively clone layout.
B: **Correct:** The shared nested layout object is modified through copy.layout.
C: **Incorrect:** No statement deletes layout or sidebar.
D: **Incorrect:** Copying an object containing nested objects with spread is valid JavaScript.
What will be the output of above code on the browser’s console?
6406537086616.
1 → 2 → 3: done → 4
6406537086617.
1 → 4 → 2 → 3: done
6406537086618.
1 → 2 → 4 → 3: done
6406537086619.
1 → 2 → 4 (3 never prints due to unresolved promise)
Published solution
**1. Enter the async function:** fetchData runs synchronously until its first await. It prints 1.
**2. Execute the Promise constructor:** A Promise's executor runs immediately. It schedules a one-second timer and then prints 2. The function suspends at await because the Promise is not yet resolved.
**3. Continue the caller:** The next outer statement prints 4 while fetchData is suspended.
**4. Resume after resolution:** The timer resolves the Promise with 'done'. The continuation prints 3: done. Final order: 1 → 2 → 4 → 3: done.
**Answer: C.**
A: **Incorrect:** The outer 4 is not blocked while the async function waits.
B: **Incorrect:** The Promise executor prints 2 synchronously, before the outer 4.
C: **Correct:** This follows synchronous execution, suspension at await and eventual continuation.
D: **Incorrect:** The timer explicitly resolves the Promise after one second.
**1. Recall a Vuex mutation:** A mutation handler receives state as its first argument and synchronously changes that state. Components trigger it with store.commit.
**2. Check the options:** A directly pushes the product into state.cart during the handler call. B defers the change using setTimeout. C performs it after fetch completes. D performs it in a Promise continuation.
**3. Explain the restriction:** Deferred changes cannot be reliably associated with the mutation's immediate before-and-after snapshots in debugging. Put asynchronous work in an action and commit a synchronous mutation when the result is ready.
**Answer: A.**
A: **Correct:** The cart update takes place synchronously within the mutation handler.
B: **Incorrect:** The actual update is deferred to a timer callback.
C: **Incorrect:** The update is deferred until the network Promise resolves.
D: **Incorrect:** Even an already-resolved Promise executes its then handler asynchronously.
**1. Read HTML data attributes:** data-price="499" is available as element.dataset.price. dataset exposes text, so its value is the string "499".
**2. Convert deliberately:** Number("499") produces the number 499. Without this conversion, a later + operation could concatenate strings instead of adding numbers.
**3. Read content and collections:** getElementById('title').innerText reads the visible text 'Vue Book'. querySelectorAll('.card') returns a NodeList, even if it contains only one matching element. querySelector, without All, returns the first element.
**Answer: A, B, C.**
A: **Correct:** dataset.price reads the attribute as a string.
B: **Correct:** Number explicitly converts that numeric string into a number.
C: **Correct:** The selected span contains the visible text Vue Book.
D: **Incorrect:** querySelectorAll returns a collection, not a single element.
A Vue frontend, a mobile app, and another backend service all call the same Flask API deployed on
multiple servers. The team chooses JWT authentication.
Which of the following statements are correct?
6406537086608.
Each request can carry the token, so any server can validate it without storing
a per-user session in memory.
6406537086609.
JWT is API-friendly because clients can send it using the
header.
6406537086610.
In Flask-JWT-Extended,
can read the identity stored in
the token.
6406537086611.
Session-based authentication is usually easier to scale across multiple servers
because no shared storage is needed. The team should have chosen this.
Published solution
**1. Understand token-based requests:** A signed JWT can carry an identity and other claims. A server validates its signature, expiration and other required claims using the appropriate trusted key and configuration.
**2. Apply it across servers:** Each server can validate the supplied token without keeping that user's session in that server's process memory. API clients commonly transmit it as Authorization: Bearer <token>.
**3. Read the Flask identity:** In Flask-JWT-Extended, get_jwt_identity() reads the identity from an appropriately verified request token.
**4. Compare sessions carefully:** Traditional server-side sessions generally need shared storage or routing coordination across instances. Some frameworks use signed client-side session cookies, so not all session designs are identical. JWT revocation or other application features can also require server-side state.
**Answer: A, B, C.**
A: **Correct:** Signature-based validation can work independently on every configured API server.
B: **Correct:** The Bearer authorization header is suitable for web, mobile and backend clients.
C: **Correct:** This helper reads the verified token identity in Flask-JWT-Extended.
D: **Incorrect:** The blanket claim that server-side sessions need no shared state across servers is false.
A Vue 2 component does the following:
• loads initial task data from an API,
• starts a timer after the component appears on the page,
• clears that timer before the component is removed.
Which hook choices are appropriate?
6406537086596.
for loading initial data.
6406537086597.
for starting DOM-related work or timers.
6406537086598.
for cleanup.
6406537086599.
for declaring reactive
.
Published solution
**1. created:** In Vue 2, component data, methods and reactive setup are available by created. It is an appropriate place to request initial task data that does not need mounted DOM elements.
**2. mounted:** At mounted, the component has been inserted into the DOM. DOM-related initialization or a timer that should start when the component appears belongs here.
**3. beforeDestroy:** Clean up timers with clearInterval or clearTimeout before destruction, so they do not continue updating a removed component.
**4. Reactive data:** Declare initial reactive properties in data(), not in destroyed(). destroyed runs after the component has been torn down.
**Answer: A, B, C.**
A: **Correct:** Initial data fetching can begin after reactive component creation.
B: **Correct:** This hook is appropriate for work that requires the mounted component.
C: **Correct:** Cleanup before teardown prevents timers from running after removal.
D: **Incorrect:** Reactive component state should be declared in data(), not after destruction.
can be used to organize nested routes under a parent route.
6406537086601.
can act as a fallback for unknown routes.
6406537086602.
tries to go back one step in browser history.
6406537086603.
Vue Router removes the need for route components.
Published solution
**1. Nested routes:** The children field inside a route definition describes nested route records. Their views are rendered in the appropriate nested router-view.
**2. Fallback route:** In the Vue Router version used by this question, a '*' route can map unmatched URLs to NotFound. Place the fallback after more specific routes. Newer major versions use different catch-all syntax.
**3. History navigation:** this.$router.go(-1) asks the browser to move back one history entry. It depends on the available history; it does not name a fixed destination.
**4. Components remain necessary:** The router maps URLs to route components; it does not replace the components that render each view.
**Answer: A, B, C.**
A: **Correct:** children is the nested route configuration field.
B: **Correct:** The catch-all route can provide the intended fallback in the shown router version.
C: **Correct:** A negative history offset requests backward navigation.
D: **Incorrect:** Routes still render components; the router only coordinates navigation and matching.
Fill in **Code1**, inside a mutation handler, which can be used to reduce the price of each of the
products in the state by a certain discount.
app.js:
**1. Use the mutation argument:** A mutation receives its state object directly as the parameter state. Therefore the products are state.products, not this.$store.state.products or a property of commit/dispatch.
**2. Apply a percentage discount:** For old price p and discount percentage d,
\[\text{new price}=p-\frac{d}{100}p.\]
The required loop is state.products.forEach(product => { product.price -= (state.discount/100)*product.price; }).
**3. Check the supplied values:** The 10% discount changes apple from 120 to 108 and banana from 60 to 54. Mutating each product property updates the stored product objects.
**Answer: B.**
A: **Incorrect:** The mutation already receives state; this.$store is not the mutation-handler access pattern shown here.
B: **Correct:** This reads the supplied state and subtracts each product's percentage discount.
C: **Incorrect:** commit is the mechanism for invoking mutations, not the products state object.
D: **Incorrect:** dispatch invokes actions; it does not contain the products array.
Consider the following Vuex store and component code.
store.js
Component.vue
After triggering all three methods (
,
and
) one by one, which
of the following statements is **correct**?
6406537086624.
All three methods will update the cart and all changes will be visible in Vue
DevTools mutation history.
6406537086625.
Only
and
will appear in Vue DevTools mutation
history, but
will appear with a delay.
6406537086626.
Only
will update the cart because mutations cannot be called
directly from components.
6406537086627.
will throw an error because Vuex prevents direct state
modification.
Published solution
**1. Direct commit:** addItem_A commits ADD_TO_CART immediately. The mutation pushes its product and appears in the Vuex mutation history.
**2. Action dispatch:** addItem_B dispatches addToCart. The action waits 500 ms and then commits ADD_TO_CART. The committed mutation appears later in the history. Dispatching an action is not itself a state mutation, but its eventual commit is recorded.
**3. Direct state access:** addItem_C pushes directly into this.$store.state.cart. Without strict mode, it can change the array, but it bypasses the mutation history. Strict mode can report such misuse; strict mode is not enabled in the displayed store.
Thus A and the delayed commit caused by B are the recorded mutation-based updates.
**Answer: B.**
A: **Incorrect:** The direct push in C bypasses committed mutations and is not recorded as a mutation.
B: **Correct:** A commits immediately, while B causes a commit after the timer delay.
C: **Incorrect:** Components are allowed to call store.commit directly; A is valid.
D: **Incorrect:** The displayed store does not enable strict mode, and Vuex does not universally prevent direct writes.
**1. beforeCreate:** Vue has not yet initialized data properties. Reading this.message gives undefined, so the first log is A: undefined.
**2. created:** data() has now supplied message:"". The log happens before the assignment, so the second log is B followed by the empty string. Then this.message is set to 'Hello from Vue!'.
**3. mounted:** The initial rendered paragraph reflects the message set during created. Reading its textContent produces 'Hello from Vue!', so the last log is C: Hello from Vue!.
The exact sequence is therefore A: undefined → B: "" → C: Hello from Vue!.
**Answer: C.**
A: **Incorrect:** beforeCreate cannot read an already initialized empty-string data property, and created logs before assigning the greeting.
B: **Incorrect:** The second log still sees the empty string because it precedes the assignment.
C: **Correct:** This follows the initialization boundary and the order of the statements in created.
D: **Incorrect:** Data has been initialized by created, so its value is not undefined there.
E: **Incorrect:** The first log occurs before data initialization and therefore is not the empty string.
**1. Match the route:** The configured path is /profile/:username. A colon-prefixed segment is a route parameter. For /profile/Ashish, the matched username parameter is 'Ashish'.
**2. Distinguish route and router:** this.$route describes the current matched route and contains its params and query. this.$router is the navigation service with methods such as push and go.
**3. Read the parameter:** Use this.$route.params.username. A query string such as ?username=Ashish would instead be read from this.$route.query.username, but that is not the path parameter configured here.
**Answer: B.**
A: **Incorrect:** $router is the navigation instance, not the current route object holding params.
B: **Correct:** $route.params.username reads the named dynamic path segment.
C: **Incorrect:** The navigation instance does not expose current-route query values this way.
D: **Incorrect:** query refers to the query string, whereas :username is a dynamic path segment.
**1. Read the actual route record:** Settings has path '/settings', name 'Settings' and component SettingsComponent. These three fields serve different purposes.
**2. Use a named navigation target:** this.$router.push({name:'Settings'}) matches the route by its registered name. Alternatively, navigating by path would require {path:'/settings'}.
**3. Reject the distractors:** 'SettingsComponent' is the component reference, not a registered route name. 'Settings' without the leading slash is not the configured absolute path. The correct object for Line B is {name:'Settings'}.
**Answer: C.**
A: **Incorrect:** The configured path is /settings, not Settings.
B: **Incorrect:** A component name is not the route path.
C: **Correct:** The route is explicitly registered with name Settings.
D: **Incorrect:** The route name is Settings, not SettingsComponent.