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 equations essential for the "Diploma Level: Modern Application Development II" exam, along with Mermaid knowledge graphs to visualize relationships.
Key Concepts:
async/await, Promise, Promise.all, Promise.race, .then(), .catch(), .finally().Critical Code Snippets:
// Promise chaining
new Promise((resolve, reject) => { /* ... */ })
.then(data => { /* ... */ })
.catch(error => { /* ... */ })
.finally(() => { /* ... */ });// Promise.all (parallel execution) Promise.all([promise1, promise2]).then(results => { /* ... */ });
// Promise.race (first to resolve/reject) Promise.race([promise1, promise2]).then(winner => { /* ... */ }); ```
Execution Order:
await pauses execution until the Promise resolves..then() and .catch() are microtasks (higher priority than setTimeout).Reactive Data:
data(), computed, or using Vue.reactive() (Vue 3).Vue.set or this.$set in Vue 2).Computed Properties:
Example:
computed: {
filteredTasks() {
return this.tasks.filter(task => task.status !== 'complete');
}
}Parent-Child Communication:
$emit, child → parent).Slots:
<slot></slot><slot name="header"></slot>Scoped slots: Pass data from child to parent.
<template v-slot:header="slotProps">
{{ slotProps.user.name }}
</template>Actions: Asynchronous operations (can commit mutations).
actions: {
fetchData({ commit }) {
return api.call().then(response => {
commit('SET_DATA', response);
});
}
}Dynamic Routes:
{ path: '/user/:id', component: UserProfile }Navigation Methods:
this.$router.push() (adds to history).this.$router.replace() (replaces current route).this.$router.go(-1) (goes back).Named Routes:
this.$router.push({ name: 'UserProfile', params: { id: 123 } });@cache.cached() (Flask-Caching):
Setup:
from celery import Celery
app = Celery('tasks', broker='redis://localhost:6379/0')Task Definition:
@app.task
def send_email(to, body):
# Async email logic
return TrueFlask-CORS Setup:
from flask_cors import CORS
CORS(app, resources={r"/api/*": {"origins": "http://example.com"}})OPTIONS request before actual request.Producer-Consumer Model:
Use Cases:
How It Works:
POST request to a predefined URL (webhook endpoint).Example:
// E-commerce order webhook
fetch("https://third-party-service/webhook", {
method: "POST",
body: JSON.stringify({ orderId: 123, status: "placed" })
});Mitigation Strategies:
npm audit, yarn audit.localStorage vs sessionStorage:
localStorage: Persists across sessions.sessionStorage: Cleared when tab closes.Limitations:
HttpOnly cookies or backend storage).this Bindingthis (inherits from parent scope).Regular Functions: this depends on how it’s called.
const obj = {
value: 10,
regular: function() { return this.value; }, // 10
arrow: () => this.value // undefined (or global/window in non-strict mode)
};Object Destructuring:
const { name, ...rest } = user; // rest = { age: 25, city: 'Boston' }Spread Operator:
const newUser = { ...user, location: user.city }; // Shallow copyWhile this exam is primarily coding/conceptual, here are logical flow equations for async and reactivity:
TotalTime(Promise.all) = Max(Promise1, Promise2, ..., PromiseN) TotalTime(Promise.race) = Min(Promise1, Promise2, ..., PromiseN) `` If (dataPropertyChanges) { RecomputeComputedProperties(); UpdateVirtualDOM(); PatchRealDOM(); } `` If (request in cache) { return cachedResponse; } else { executeRoute(); cacheResponse(); } ``