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 and amswer 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 equations for the "Modern Application Development II" exam, followed by Mermaid knowledge graphs to visualize relationships.
Key Concepts:
async/await, Promise, .then(), .catch(), .finally().Promise Methods:
Promise.all(): Waits for all promises to resolve (fails if any reject).Promise.race(): Resolves/rejects as soon as the first promise settles.Promise.allSettled(): Waits for all promises to settle (resolved/rejected).this Binding:
this depends on how the function is called.this is lexically scoped (inherits from parent).Example Code Outputs:
// Closure Example
function createCounter() {
let count = 0;
return function() { count++; return count; };
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2// Promise Race Example const team = Promise.all([task1, task2]).then(() => "Team"); const mayur = new Promise(resolve => setTimeout(resolve, 2000, "Mayur")); Promise.race([team, mayur]).then(winner => console.log(winner)); ```
data(), computed, watch.Caveats:
arr[0] = 1) or object properties (e.g., obj.newProp = 1) won’t trigger reactivity unless using Vue.set or spreading ({...obj}).Slots: Distribute content from parent to child.
<slot name="header">.<slot :data="item">).Key Rules:
: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).this.$router.go(-1): Navigates back.name instead of path for navigation.Object Syntax:
<div :class="{ active: isActive, 'text-bold': hasBoldText }"></div>Array Syntax:
<div :class="[isActive ? 'active' : '', errorClass]"></div>created(): After instance creation (data/props available).mounted(): After DOM insertion.updated(): After reactive data changes.beforeDestroy(): Before teardown.@cache.cached(): Skips route execution for repeated inputs (reduces server load).Flask-CORS Setup:
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://example.com"}})Key Methods:
task.delay(): Schedule a task.task.get(): Get result (blocks until ready).Benefits:
Webhooks vs. Polling:
Critical Rendering Path:
Mitigations:
package.json).Fix: Restrict origins explicitly:
CORS(app, resources={r"/api/*": {"origins": ["https://trusted.com"]}})localStorage vs. sessionStorage:
localStorage: Persists across sessions (vulnerable to XSS).sessionStorage: Cleared when tab closes.HttpOnly cookies for sensitive data.How it Works:
data properties into getters/setters (Proxy in Vue 3).{{ message }}.Directives:
v-if/v-show: Conditional rendering.v-for: Loop over arrays/objects.v-bind: Bind attributes (:class, :style).v-on: Event listeners (@click).| Computed | Watched |
|---|---|
| Cached (recomputes only if dependencies change). | Runs on specific data changes. |
| Use for derived data. | Use for async/side effects. |
const { name, ...rest } = user; // Extract `name`, rest in `rest`
const newUser = { ...rest, location: city }; // Spread operator
this binding: Inherits from parent scope.() => expression.export default or named exports (export const x = 1).import x from './module' or import { x } from './module'.// Team wins if both Prashant and Nikita finish before Mayur
const team = Promise.all([prashant, nikita]).then(() => "Team");
const winner = await Promise.race([team, mayur]);
// Mutation (synchronous)
mutations: {
SET_USER(state, user) {
state.user = user;
}
},
// Action (asynchronous)
actions: {
async fetchUser({ commit }, id) {
const user = await api.getUser(id);
commit('SET_USER', user);
}
}
from flask_caching import Cache
cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache'})
@app.route('/expensive')
@cache.cached(timeout=60) # Cache for 60 seconds
def expensive():
return compute_expensive_result()
// Won't trigger reactivity:
this.myObject.newProp = 'value'; // Bad
this.myArray[0] = 1; // Bad
// Good (reactive):
this.$set(this.myObject, 'newProp', 'value');
this.myArray.splice(0, 1, 1);
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={
r"/api/*": {
"origins": ["http://localhost:3000", "https://trusted.com"]
}
})