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 core topics, concepts, and principles for the "Modern Application Development II" exam, along with Mermaid knowledge graphs to visualize relationships.
Key Concepts:
Promise states: pending, fulfilled, rejected.Promise.all(): Waits for all promises to resolve (fails if any reject).Promise.race(): Resolves/rejects as soon as the first promise settles.async/await: Syntactic sugar for promises; await pauses execution until the promise resolves.setTimeout).Critical Code Snippets:
// Promise chaining
new Promise((resolve, reject) => { /* ... */ })
.then(data => { /* ... */ })
.catch(error => { /* ... */ })
.finally(() => { /* ... */ });// Promise.all vs. Promise.race Promise.all([promise1, promise2]); // Waits for all Promise.race([promise1, promise2]); // First to settle
// Async/await async function fetchData() { const data = await somePromise(); console.log(data); } ```
Reactivity:
data and updates the DOM automatically.data() are reactive; use Vue.set or spread operator for dynamic properties.filteredTasks).watch: { someData(newVal) { ... } }).Components & Props:
<slot>, named slots, scoped slots).created, mounted, updated, destroyed.Vuex (State Management):
commit).dispatch); can call mutations.Vue Router:
:id in paths (e.g., /user/:id).this.$router.push(), this.$router.replace().name instead of path for flexibility.query: { key: value }.Class/Style Bindings:
<div :class="{ active: isActive, 'text-bold': hasBoldText }"></div>Key Metrics:
Optimization Techniques:
@cache.cached() in Flask).Tools:
Flask Basics:
@app.route('/path').@cache.cached() skips repeated route execution.CORS: Enable with flask_cors; restrict origins for security.
CORS(app, resources={r"/api/*": {"origins": "http://example.com"}})Celery for Async Tasks:
time.sleep() in synchronous routes.Purpose:
Webhooks vs. Polling:
Message Brokers (e.g., RabbitMQ):
Supply Chain Attacks:
Mitigations:
package.json).latest tags; use exact versions.CORS:
Access-Control-Allow-Origin: * in production.Environment Variables:
.env (never in code).Destructuring:
const { name, ...rest } = user; // Extract `name`, rest in `otherInfo`Arrow Functions:
this (inherits from parent scope).function() for this binding).Closures:
Storage APIs:
localStorage: Persists across sessions.sessionStorage: Cleared when tab closes.JSON.parse/JSON.stringify).Vue Reactivity Caveats:
Vue.set or spread operator.Promise Pitfalls:
.catch()).async/await errors can be caught with try/catch.Flask CORS Errors:
CORS config.Vue Router:
replace() vs. push(): replace doesn’t add to history stack.While this exam is primarily conceptual, here are pseudo-equations for critical logic:
Promise Race/All Time Complexity:
Promise.all: T_total = max(T1, T2, ..., Tn)Promise.race: T_total = min(T1, T2, ..., Tn)Vue Reactivity:
Reactive Update = f(Data Change) → DOM UpdateFlask Caching:
Cache Hit Ratio = (Hits) / (Hits + Misses)Webhook vs. Polling Efficiency:
Webhook Latency ≈ 0 (push-based).Polling Latency = Polling Interval / 2 (average).Vue.js:
methods, computed, and watch.v-if vs. v-show: v-if removes DOM elements; v-show toggles display: none.JavaScript:
let vs. const: let is reassignable; const is block-scoped but not immutable for objects/arrays.this; use function() for object methods.Flask/Celery:
Performance:
Security: