Home / Past papers / MAD2 End Term / this paper

What will be the order of console output when the following JavaScript code is executed?
```javascript
async function test() {
console.log("P");
await Promise.resolve();
console.log("Q");
}
console.log("R");
test();
console.log("S");
```
Consider the following JavaScript program:
```javascript
const user = {
name: 'Alice',
age: 25,
city: 'Boston',
country: 'USA'
};
const { name, city, ...otherInfo } = user;
const newUser = { name, location: city, ...otherInfo };
console.log(name);
console.log(otherInfo);
console.log(newUser);
```
What will be the output of the above program?
```
Alice
{ city: 'Boston', age: 25, country: 'USA' }
{ name: 'Alice', location: 'Boston', city: 'Boston', age: 25,
country: 'USA' }
```
```
Alice
{ age: 25, country: 'USA' }
{ name: 'Alice', location: 'Boston', city: 'Boston', age: 25,
country: 'USA' }
```
```
Alice
{ age: 25, country: 'USA' }
{ name: 'Alice', location: 'Boston', age: 25, country: 'USA' }
```
```
undefined
{ name: 'Alice', city: 'Boston', age: 25, country: 'USA' }
{ name: 'Alice', location: 'Boston' }
```
Consider the following javascript program.
What will be the output of the above program on the browser’s console?```javascript
new Promise((resolve, reject) => {
const score = 0.45;
if (score >= 0.5) {
resolve(score);
} else {
reject(new Error("Score too low"));
}
})
.then(data => {
console.log("Stage A:", data);
return data * 10;
})
.catch(error => {
console.log("Stage B:", error.message);
return 3;
})
.then(data => {
console.log("Stage C:", data);
if (data < 5) {
throw new Error("Value below threshold");
}
return data + 2;
})
.then(data => {
console.log("Stage D:", data);
return data / 2;
})
.catch(error => {
console.log("Stage E:", error.message);
if (error.message === "Value below threshold") {
return "Recovered";
}
throw error;
})
.then(data => {
console.log("Stage F:", data);
if (data === "Recovered") {
return 10;
}
return data * 4;
})
.finally(() => {
console.log("Stage G: Cleanup completed");
});
```
```text Stage A: 0.45 Stage C: 4.5 Stage D: 6.5 Stage F: 26 Stage G: Cleanup completed ```

```text Stage B: Score too low Stage C: 3 Stage E: Value below threshold Stage F: Recovered Stage G: Cleanup completed ```

Stage A: 0.45 Stage C: 4.5 Stage E: Value below threshold Stage F: Recovered Stage G: Cleanup completed

``` Stage B: Score too low Stage C: 3 Stage D: 5 Stage F: 20 Stage G: Cleanup completed ```

Consider this HTML and Vue setup:
index.html
```html
<div id="app1">{{ message }}</div>
<div id="app2">{{ message }}</div>
<script src="app.js" ></script>
```
app.js
```javascript
new Vue({
el: '#app1',
data: { message: 'Hello from App 1' }
});
new Vue({
el: '#app2',
data: { message: 'Hello from App 2' }
});
```
What will be rendered on the browser?
Consider the following JavaScript code running in a browser:
```javascript
localStorage.setItem('score', '10');
sessionStorage.setItem('multiplier', '3');
for (let i = 0; i < 2; i++) {
let score = localStorage.getItem('score');
let multiplier = sessionStorage.getItem('multiplier');
score = score + 5;
multiplier = multiplier * 2;
localStorage.setItem('score', score);
sessionStorage.setItem('multiplier', multiplier);
}
console.log(localStorage.getItem('score'));
console.log(sessionStorage.getItem('multiplier'));
```
What will be the output in the browser console?
20 12

20 NaN

NaN 12

None of these

Consider the below Vue class binding and select the most appropriate option(s):
```html
<div v-bind:class="{ active: isActive, 'text-bold': hasBoldText, disabled: !isEnabled }"></div>
```
Scenario
1. The component is loaded. 2. User clicks "Mark Complete" for the task named Build Project.
3. User clicks "Show Completed" button again.


The `filteredTasks` logic won't work properly if we used arrow functions for the `filter` method.

Using non-arrow functions in computed properties allows correct this access to Vue instance.

``` filteredTasks and completedCount will both update reactively when a task's status is changed. ```

The `@click='markComplete(task.id)'` usage correctly preserves reactivity.

Consider the following JavaScript code:
```javascript
const globalVar = 100;
var value = 200;
const calculator = {
value: 50,
compute: function() {
const innerObj = {
value: 25,
regularMethod: function() {
return this.value;
},
arrowMethod: () => {
return this.value;
},
mixedMethod: function() {
const arrowInside = () => this.value;
return arrowInside();
}
};
return {
regular: innerObj.regularMethod(),
arrow: innerObj.arrowMethod(),
mixed: innerObj.mixedMethod()
};
}
};
const result = calculator.compute();
console.log(result.regular);
console.log(result.arrow);
console.log(result.mixed);
```
Assuming this code runs in a browser environment, what will be the output?
25 200 50

25 50 25

50 200 50

25 200 25

Consider this Vue.js component code:
```javascript
const TodoApp = {
template: `
<div>
<input v-model="newTodo" @keyup.enter="addTodo" />
<ul>
<li v-for="todo in todos" :key="todo.id">{{ todo.text }}</li>
</ul>
</div>
`,
data() {
return {
newTodo: '',
todos: []
}
},
methods: {
addTodo() {
if (this.newTodo) {
this.todos.push({ id: Date.now(), text: this.newTodo });
this.newTodo = '';
}
}
}
}
```
What happens when a user types "Learn Vue" into the input field and presses Enter?
Note: The `@keyup.enter` directive calls `addTodo()` when the Enter key is pressed.
An error occurs because the todos array is empty

The input is cleared, and Learn Vue appears in the list

Only the input is cleared, no todo is added

The page refreshes

Given this Vue Router setup:
```javascript
const routes = [
{ path: '/user/:id/profile', component: UserProfile },
{ path: '/user/:id', component: User },
{ path: '*', component: NotFound },
{ path: '/user/:id/settings', component: UserSettings },
];
```
What component renders for URL /user/123/settings?
Given the Flask app:
```python
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})
@app.route('/api/data')
def data():
return {"msg": "Success"}
```
frontend code:
```javascript
fetch("http://localhost:5000/api/data")
.then(res => res.json())
.then(data => console.log(data));
```
What will happen when run from a Vue app hosted at http://localhost:5173?
What will this JavaScript code output?
```javascript
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter1 = createCounter();
const counter2 = createCounter();
console.log(counter1());
console.log(counter1());
console.log(counter2());
```
1 2 3

1 2 1

``` 1 1 1 ```

``` undefined undefined undefined ```

Consider the following Vue component structure with nested components and
complex slot configurations:
```javascript
Vue.component('data-provider', {
template: `
<div class="provider">
<slot name="header" :user="currentUser" :loading="isLoading"></slot>
<slot name="content" :items="filteredItems" :count="itemCount"></slot>
<slot :fallback="defaultMessage" :error="errorState"></slot>
</div>
`,
data() {
return {
currentUser: { name: 'John', role: 'admin' },
isLoading: false,
filteredItems: ['item1', 'item2', 'item3'],
itemCount: 3,
defaultMessage: 'No data available',
errorState: null
}
}
});
Vue.component('parent-component', {
template: `
<data-provider>
<template v-slot:header="{ user, loading }">
<h1 v-if="!loading">Welcome {{ user.name }}</h1>
<span v-else>Loading...</span>
</template>
<template v-slot:content="slotProps">
<ul>
<li v-for="item in slotProps.items" :key="item">
{{ item }} ({{ slotProps.count }} total)
</li>
</ul>
</template>
<template v-slot:default="defaultProps">
<p>{{ defaultProps.fallback }}</p>
</template>
</data-provider>
`
});
```
Now consider this usage of the parent-component:
```html
<div id="app">
<parent-component></parent-component>
</div>
```
Consider the following Vue Router configuration in a Vue 2 application:
In a Vue component, you have these navigation methods:
Consider the following Vue Router configuration in a Vue 2 application:
In a Vue component, you have these navigation methods: What URLs will be generated when the user clicks each navigation element?```javascript
const routes = [
{
path: '/',
name: 'Home',
component: HomeView
},
{
path: '/user/:id',
name: 'UserProfile',
component: UserProfile
},
{
path: '/product/:category/:id',
name: 'ProductDetail',
component: ProductDetail
}
];
```
```html
<template>
<div>
<button @click="goToUser">View User</button>
<button @click="goToProduct">View Product</button>
<router-link :to="{ name: 'Home' }">Home</router-link>
</div>
</template>
<script>
export default {
methods: {
goToUser() {
this.$router.push({ name: 'UserProfile', params: { id: 123 } });
},
goToProduct() {
this.$router.push({ name: 'ProductDetail',
params: { category: 'electronics', id: 456}
});
},
navigateOne() {
this.$router.push({ name: 'UserProfile', params: { id: 555 },
query: { tab: 'settings'}
});
},
navigateTwo() {
this.$router.replace({ name: 'Home' });
},
goBack() {
this.$router.go(-1);
}
}
}
</script>
```
Prashant and Nikita are creating a quiz question paper collaboratively. They are each working on different sections — and complete their tasks in parallel. Meanwhile, Mayur is enjoying a single-player game that finishes when the game loop ends.
To compare productivity:
● If Prashant and Nikita (together) finish faster than Mayur, the winner is "Team". ● If Mayur finishes faster, he wins. ● If both take the same time, Mayur wins by default.
You are simulating this scenario in the browser.Prashant and Nikita are represented using parallel Promises. Mayur is represented using a single Promise. The frontend must calculate who finishes first using asynchronous logic, and display the result.
Based on the above data, answer the given subquestions. 
app2.js
```javascript
async function playGame() {
const start = Date.now();
const prashantPromise = new Promise(resolve =>
setTimeout(resolve, 3000));
const nikitaPromise = new Promise(resolve =>
setTimeout(resolve, 2000));
const mayurPromise = new Promise(resolve =>
setTimeout(resolve, 2000));
await Promise.all([prashantPromise, nikitaPromise]);
const teamTime = Date.now() - start;
await mayurPromise;
const mayurTime = Date.now() - start;
const winner = (teamTime < mayurTime) ? "Team" : "Mayur";
console.log(`Winner is: ${winner}`);
}
```Auto-generated summary from the source site. Handy as a checklist; the lessons above explain each idea from scratch.
Here’s a structured summary of the core topics, concepts, principles, and key takeaways from the exam questions, along with a Mermaid knowledge graph to visualize relationships.
Key Concepts:
Promise.race(): Resolves/rejects as soon as one promise settles.Promise.all(): Waits for all promises to resolve (or any to reject).async/await: Syntactic sugar for promises; await pauses execution until the promise settles.setTimeout).Critical Code Snippets:
// Promise chaining with .then()/.catch()
new Promise((resolve, reject) => { ... })
.then(data => { ... })
.catch(error => { ... });// Promise.race vs. Promise.all Promise.race([teamPromise, mayurPromise]).then(winner => { ... }); Promise.all([prashant, nikita]).then(() => "Team"); ```
Common Pitfalls:
"10" + 5 = "105").this binding in arrow functions (lexical scoping) vs. regular functions (dynamic scoping).Reactivity:
data() properties) changes.filteredTasks).Slots & Scoped Slots:
<template v-slot:name> for targeted content insertion.v-slot:header="{ user }").Vue Router:
:id in paths (e.g., /user/:id).Navigation Methods:
this.$router.push(): Adds to history stack.this.$router.replace(): Replaces current entry (no history stack addition).this.$router.go(-1): Navigates back.name instead of path for decoupling.Vuex:
Critical Code Snippets:
<!-- Scoped Slots -->
<data-provider>
<template v-slot:header="{ user }">
<h1>Welcome {{ user.name }}</h1>
</template>
</data-provider><!-- Vue Router Navigation --> this.$router.push({ name: 'UserProfile', params: { id: 123 } }); ```
Caching:
@cache.cached(): Skips route execution for repeated inputs (reduces server load).CORS (Cross-Origin Resource Sharing):
Flask-CORS Setup:
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})Celery for Async Tasks:
Security:
Lighthouse Metrics:
Optimization Strategies:
Use Cases:
Webhooks:
Critical Scenarios:
Destructuring:
const { name, city, ...otherInfo } = user;Spread Operator:
const newUser = { name, location: city, ...otherInfo };Arrow Functions:
this binding (no dynamic context).localStorage vs. sessionStorage:
localStorage: Persists across sessions.sessionStorage: Cleared when tab closes.Pitfalls:
// Team wins if both Prashant and Nikita finish before Mayur
const teamTime = Math.max(prashantTime, nikitaTime);
const winner = (teamTime < mayurTime) ? "Team" : "Mayur";
// Computed property updates when dependencies change
filteredTasks() {
return this.showCompleted ? this.tasks : this.tasks.filter(t => t.status !== 'complete');
}
### Allow only specific origins
CORS(app, resources={r"/api/*": {"origins": "http://example.com"}})
Lighthouse Score = f(FCP, TTI, CLS, ...)
| Topic | Key Concepts to Review | Practice |
|---|---|---|
| Promises/Async JS | Promise.race, Promise.all, async/await, closures, event loop | Write promise chains; simulate race conditions. |
| Vue.js | Reactivity, slots (default/named/scoped), Vue Router, Vuex (actions/mutations) | Build a component with scoped slots; implement dynamic routing. |
| Flask | Caching decorators, CORS setup, Celery tasks, security (version pinning) | Configure CORS for a Flask API; write a Celery task. |
| Web Performance | Lighthouse metrics (FCP, TTI, CLS), optimization techniques | Audit a webpage with Lighthouse; reduce HTTP requests. |
| Message Queues | Webhooks vs. polling, brokers (scalability, batch processing) | Design a notification system using webhooks. |
| JavaScript ES6+ | Destructuring, spread operator, arrow functions (this binding) | Refactor code to use destructuring/spread. |
| Browser Storage | localStorage vs. sessionStorage, string storage limitations | Store/retrieve objects in localStorage. |
Promise.race (first settles) and Promise.all (all settle)."10" + 5 = "105").