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 (where applicable) for the "Diploma Level: Modern Application Development II" exam, along with Mermaid knowledge graphs to visualize relationships.
Key Concepts:
async/await, Promise.all(), Promise.race(), .then(), .catch(), .finally().setTimeout, fetch) are handled.Critical Code Snippets:
// Promise chaining
new Promise((resolve, reject) => { /* ... */ })
.then(data => { /* ... */ })
.catch(error => { /* ... */ })
.finally(() => { /* ... */ });// Promise.all (waits for all promises) Promise.all([promise1, promise2]).then(values => { /* ... */ });
// Promise.race (resolves/rejects when the first promise settles) Promise.race([promise1, promise2]).then(value => { /* ... */ }); ```
Example Outputs:
Promise.race([teamPromise, mayurPromise]) resolves, the fastest determines the winner.Promise.all waits for all promises (e.g., Prashant and Nikita working in parallel).Key Concepts:
data(), computed).Directives:
v-model (two-way binding), v-for (loops), v-if/v-show (conditional rendering).@click, @keyup.enter (event handlers).Components & Slots:
<slot name="header">), scoped slots (v-slot:header="slotProps").Vuex:
state → getters → actions → mutations.Vue Router:
/user/:id), named routes, router.push() vs. router.replace().router-link for declarative navigation.Critical Code Snippets:
// Vuex Store Structure
const store = new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++; }
},
actions: {
async fetchData({ commit }) {
const response = await fetch('api/data');
commit('updateData', response.data);
}
}
});// Vue Router Configuration const routes = [ { path: '/user/:id', name: 'UserProfile', component: UserProfile }, { path: '/product/:category/:id', component: ProductDetail } ]; ```
Key Concepts:
Lighthouse Metrics:
Optimization Techniques:
@cache.cached()).Critical Tools:
Key Concepts:
CORS (Cross-Origin Resource Sharing):
flask_cors).CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}}).Caching:
@cache.cached() skips route execution for repeated inputs (reduces server load).Asynchronous Tasks:
time.sleep() in Flask routes).Critical Code Snippets:
from flask import Flask
from flask_cors import CORS
from flask_caching import Cacheapp = Flask(_name_) CORS(app) # Allow all origins (or restrict with resources) cache = Cache(app, config={'CACHE_TYPE': 'simple'})
@app.route('/api/data') @cache.cached(timeout=50) # Cache for 50 seconds def get_data(): return {"data": "cached_response"} ```
Key Concepts:
Message Queue: Buffer for asynchronous communication (e.g., RabbitMQ, Kafka).
Use Cases:
Webhooks:
Critical Scenarios:
E-commerce Notifications:
Key Concepts:
Supply Chain Attacks:
Critical Tools:
npm audit: Check for vulnerable dependencies..npmrc: Enforce version pinning.Key Concepts:
Critical Rules:
Example Flow:
UI → Dispatch Action → Commit Mutation → Update State → Re-render UIKey Concepts:
Destructuring:
const { name, city, ...rest } = user; // rest = { age: 25, country: 'USA' }this binding (no own this).localStorage vs. sessionStorage:
localStorage: Persists across sessions.sessionStorage: Cleared when the tab closes.JSON.parse/stringify` for objects).Key Concepts:
GET, POST, PUT, DELETE.Status Codes:
200 OK, 404 Not Found, 500 Server Error.CORS Headers:
Access-Control-Allow-Origin: Specifies allowed domains.Critical Tools:
Fetch API:
fetch('http://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
})
.then(res => res.json())
.then(data => console.log(data));Key Concepts:
While this exam is primarily conceptual, here are performance-related formulas to remember:
Total Load Time = DNS Lookup + TCP Handshake + Request/Response Time + Rendering Time `` Performance Score = 0.3*FCP + 0.3*TTI + 0.2*CLS + 0.2*Other Metrics ``Promise Race/All Time:
Promise.race: Resolves in min(T1, T2, ..., Tn).Promise.all: Resolves in max(T1, T2, ..., Tn).Vue.js:
v-slot syntax is critical for scoped slots.JavaScript:
Promise.race vs. Promise.all: Know which resolves first vs. waits for all.Flask:
@cache.cached skips route execution for repeated inputs.Message Queues:
Performance:
Security:
Focus on:
Avoid:
time.sleep() in Flask).