Home / Past papers / MAD2 End Term / this paper

Consider the below JavaScript program.
```javascript
const promise = new Promise(((resolve, reject) => {
reject('Error!');
resolve('Success!');
}));
promise.then(console.log).catch(console.log);
```
What will be the output of the above program?
Consider the below JavaScript program. ```javascript let arr = [4, 5, 6]; let sum = arr.reduce((acc, val, idx, array) => acc + (array[idx - 1] || 0), 0); console.log(sum); ``` What will be the output of the above program?

Consider the below JavaScript program.
```javascript
const obj = {
num: 8,
multiply: function () {
return this.num * 3;
},
};
const multiply = obj.multiply.bind({ num: 2 });
console.log(multiply());
```
What will be the output of the above program?
Consider the below Vuex store configuration:
```javascript
const store = new Vuex.Store({
state: {
items: ['Vue', 'React'],
},
mutations: {
removeItem(state, item) {
state.items = state.items.filter(i => i !== item);
},
},
actions: {
removeItemAsync({ commit }, item) {
setTimeout(() => {
commit('removeItem', item);
}, 500);
},
},
});
```
If the addItemAsync action is dispatched with the item 'Vue', what will be the state of items after 2 seconds?
Consider the below Vue app.
```html
<div id="app">
<router-link to="/home">Go to Home</router-link>
<router-view></router-view>
</div>
<script>
const Home = { template: '<div>Home</div>' };
const About = { template: '<div>About</div>' };
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About },
{ path: '*', redirect: '/home' }
];
const router = new VueRouter({ routes });
new Vue({
el: '#app',
router
});
</script>
```
What happens when the user navigates to an undefined route like "/random"?
Consider the following Vue component:
```javascript
Vue.component('search-component', {
data() {
return {
searchQuery: ''
}
},
watch: {
searchQuery(newQuery, oldQuery) {
this.fetchResults(newQuery)
}
},
methods: {
fetchResults(query) {
// Fetch search results
}
}
})
```
Which of the following statements is true?
Consider the following JavaScript code.
```javascript
function processArray(arr) {
let result = arr.filter(item => item > 5)
.map(item => item * 2)
.reduce((sum, item) => sum + item, );
return result;
}
```
What will be returned when processArray([2, 6, 4, 8, 3]) is called?
Examine the following JavaScript code.
```javascript
function processData() {
let data = [1, 2, 3, 4];
let result = data.forEach(item => {
if (item % 2 === 0) {
return item * 10;
}
});
return result;
}
```
What will be returned when processData() is called?
Consider the following JavaScript code.
```javascript
var value = 30;
const firstObj = {
value: 10,
displayValue: function() {
return this.value;
}
};
const secondObj = {
value: 20
};
const displayValue1 = firstObj.displayValue.apply(secondObj);
const displayValue2 = firstObj.displayValue.apply();
const displayValue3 = function() {
return firstObj.displayValue.apply(this);
}.call(secondObj);
const displayValue4 = firstObj.displayValue.bind(this)(20);
console.log("val1", displayValue1);
console.log("val2", displayValue2);
console.log("val3", displayValue3);
```
What will be the output of the above code on the browser's console?
Consider the following JavaScript code.
```javascript
export default {
data() {
return {
loginToken: '',
};
},
mounted() {
this.loginToken = sessionStorage.getItem('authToken') || '';
},
methods: {
updateToken(newToken) {
this.loginToken = newToken;
sessionStorage.setItem('authToken', newToken);
}
}
};
```
What will happen when a user calls the updateToken method with a new value and then refreshes the page?
The new token will be lost, and the "loginToken" data property will be reset to an empty string.

The new token will be preserved in session storage, and the "LoginToken" data property will be populated with the stored value on page refresh.

The method will throw an error because sessionStorage cannot be modified directly.

The "loginToken" data property will be updated, but the session storage will remain unchanged.

Consider the below Vuex setup.
```javascript
const store = new Vuex.Store({
state: {
number: 10
},
mutations: {
updateNumber(state, payload) {
state.number = payload;
}
},
actions: {
async fetchNumber({ commit }) {
const fetchedValue = await getData();
commit('updateNumber', fetchedValue);
}
}
});
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve(100), 1500);
});
}
store.dispatch('fetchNumber');
console.log(store.state.number);
```
What is logged to the console immediately after dispatching the action?
Consider the below flask SSE implementation.
```python
from flask import Flask, Response
import time
app = Flask(__name__)
def event_stream():
for i in range(5):
yield f"data: Message {i}"
time.sleep(1)
@app.route('/events')
def sse():
return Response(event_stream(), mimetype="text/event-stream")
```
And the Vue.js frontend:
```html
<template>
<div>
<p v-for="msg in messages" :key="msg">{{ msg }}</p>
</div>
</template>
<script>
export default {
data() {
return { messages: [] };
},
mounted() {
const eventSource = new EventSource("http://localhost:5000/events");
eventSource.onmessage = (event) => {
this.messages.push(event.data);
};
},
};
</script>
```
What will happen when a user opens this page?
Consider the following Flask application (server.py) and an HTML file named index.html:
server.py
```python
from flask import Flask
import time
app = Flask(__name__)
@app.route("/api/slow1")
def slow_api_1():
time.sleep(15)
return "Response from Slow API 1", 200, {'Access-Control-Allow-Origin': '*'}
@app.route("/api/slow2")
def slow_api_2():
time.sleep(25)
return "Response from Slow API 2", 200, {'Access-Control-Allow-Origin': '*'}
if __name__ == "__main__":
app.run(threaded=False)
```
index.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Flask Fetch Example</title>
</head>
<body>
<h1>Fetching API Data...</h1>
<script>
fetch("http://127.0.0.1:5000/api/slow1")
.then(res => res.json())
.then(data => console.log("API 1 Response:", data));
fetch("http://127.0.0.1:5000/api/slow2")
.then(res => res.json())
.then(data => console.log("API 2 Response:", data));
</script>
</body>
</html>
```
The application runs on http://localhost:5000.
A client makes two requests, one to http://localhost:5000/data/apple and another to http://localhost:5000/data/orange, both within 50 seconds.
What will be the approximate absolute difference between their latencies?
Consider the following Vue apps in script.js and the index.html file.
script.js
```javascript
const app1 = new Vue({
el: '#app1',
data: {
value1: "VueJS",
value2: "Frontend"
}
})
const app2 = new Vue({
el: '#app2',
data: {
value3: "JavaScript"
}
})
```
index.html
```html
<div id="app2">
{{value1}}
<div id="app1">
{{value2}}
</div>
{{value3}}
</div>
<script src="./script.js"></script>
```
What will be rendered on the browser?
Consider the following Vue App and the HTML document given below.
index.html
```html
<div id="app">
<my-comp>
<slot>Hello Frontend</slot>
<slot>Hello VueJS</slot>
</my-comp>
</div>
<script src="script.js"></script>
```
script.js
```javascript
const myComp = {
template: `
<div>
<slot></slot>
<slot></slot>
</div>
`
}
const app = new Vue({
components: {
"my-comp": myComp
}
}).$mount('#app')
```
What will be the output on the browser?
Consider the following Vue Router configuration:
```javascript
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/user/:id', component: User },
{ path: '/about', component: About },
{ path: '*', component: NotFound }
]
})
```
Which URL/URLs would render the NotFound component?
Consider the below Vuex store configuration.
```javascript
const store = new Vuex.Store({
state: {
count: 5,
},
mutations: {
decrement(state) {
state.count--;
},
},
});
```
And the below Vue component:
```html
<template>
<div>
<button @click="decrement">Decrement</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['count']),
},
methods: {
...mapMutations(['decrement']),
},
};
</script>
```
What will be displayed in the placeholder "{{ count }}" on the browser after clicking the "Decrement" button 4 times?
How many times will "Render" be logged in the console when the Vue component below is mounted?
```html
<div id="app">
<div>{{ computedValue }}</div>
</div>
<script>
new Vue({
el: "#app",
data() {
return { count: 0 };
},
computed: {
computedValue() {
console.log("Render");
return this.count * 2;
},
},
mounted() {
this.count++;
this.count++;
},
});
</script>
```

Which of the following statements
is correct for the following fetch
request.
```javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET"
})
.then(response => {
return response.json();
})
.then(data => console.log("Protected Route Response:", data))
.catch(error => console.error("Error:", error));
```
The request will be processed successfully, and "Hello, student!" will be returned.

The request will fail with a 401 Unauthorized error.

The request will return an empty response with a 200 OK status.

The request will fail with a 403 Forbidden error.

What will be the result of the
following fetch request.
```javascript
fetch("http://127.0.0.1:5000/protected", {
method: "GET",
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.."
}
})
.then(response => {
if (response.status === 403) {
throw new Error("403 Forbidden: Insufficient permissions");
}
return response.json();
})
.then(data => console.log("Protected Route Response:", data))
.catch(error => console.error("Error:", error));
```
The request will be processed successfully, and "Hello, student!" will be returned.

The request will fail with a 401 Unauthorized error.

The request will return an empty response with a 200 OK status.

The request will fail with a 403 Forbidden error.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
Consider the following Vue app with the Vue Router shown below and answer the given subquestions.
What will be rendered on the browser for the given value of localStorage?
```json
{
"token": 112,
"userRole": "admin"
}
```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 essential for the "Modern Application Development II" exam, along with a Mermaid knowledge graph to visualize relationships.
this Keyword:
this from the enclosing lexical scope (lexical this).bind(), call(), and apply() for explicit this binding.Key Equation/Concept:
// Arrow function (lexical this)
const obj = { val: 10, getVal: () => this.val }; // `this` refers to outer scope (e.g., window in browsers).Promises & Async/Await:
pending, fulfilled, rejected..then() and .catch() chaining.Key Example:
const promise = new Promise((resolve, reject) => reject("Error!"));
promise.then(console.log).catch(console.log); // Output: "Error!"Array Methods:
reduce(), map(), filter(), forEach().Key Equation:
[a, b, c].reduce((acc, val) => acc + val, initialValue); // Sums array elements.Component Lifecycle:
beforeCreate → created → beforeMount → mounted → beforeUpdate → updated → beforeUnmount → unmounted.Vuex:
state, mutations, actions, getters.dispatch and commit.Key Example:
actions: {
async fetchData({ commit }) {
const data = await apiCall();
commit('UPDATE_STATE', data);
}
}Vue Router:
:id parameters.*) for 404 handling.beforeEach, beforeEnter).Key Example:
routes: [
{ path: '/user/:id', component: User },
{ path: '*', component: NotFound }
]Slots & Scoped Slots:
Key Example:
<my-component>
<template v-slot:default>Hello</template>
</my-component>Computed Properties & Watchers:
computed: Cached, reactive dependencies.watch: Side effects on data changes.Key Example:
computed: {
fullName() { return `${this.firstName} ${this.lastName}`; }
},
watch: {
searchQuery(newVal) { this.fetchResults(newVal); }
}JWT (JSON Web Tokens):
header.payload.signature.Example Flow:
// Login → Generate JWT → Store in localStorage/sessionStorage → Attach to requests via `Authorization: Bearer <token>`.CORS (Cross-Origin Resource Sharing):
Access-Control-Allow-Origin, Access-Control-Allow-Methods.OPTIONS request for non-simple requests.Webhooks vs. APIs:
Example:
Webhook: GitHub → Jenkins (on push event).
API: Client → Weather API (on user request).Server-Sent Events (SSE):
EventSource API and text/event-stream MIME type.Key Example:
// Client
const eventSource = new EventSource("/events");
eventSource.onmessage = (e) => console.log(e.data);// Server (Flask) @app.route('/events') def sse(): return Response(event_stream(), mimetype="text/event-stream") ```
WebSockets:
Celery/RabbitMQ:
JWT Integration:
@jwt_required() decorator for protected routes.Example:
@app.route("/protected")
@jwt_required()
def protected():
current_user = get_jwt_identity()
return jsonify(message=f"Hello, {current_user}!")SSE in Flask:
Response and generators.Example:
def event_stream():
yield "data: Hello\n\n"
return Response(event_stream(), mimetype="text/event-stream")Fetch API:
GET, POST, PUT, DELETE methods.Handling responses/errors:
fetch("/api/data")
.then(res => res.json())
.catch(error => console.error(error));Authentication Flows:
localStorage (persistent) vs. sessionStorage (session-only).Example:
localStorage.setItem("token", jwtToken); // Persists across tabs.
sessionStorage.setItem("token", jwtToken); // Cleared on tab close.Client-Side Routing:
Advantages:
Disadvantages:
State Management:
this Binding| Concept | Equation/Code |
|---|---|
| Promise Rejection | new Promise((_, reject) => reject("Error")).catch(console.log); → "Error" |
Array reduce | [1, 2, 3].reduce((acc, val) => acc + val, 0); → 6 |
| Vuex Mutation | commit('INCREMENT', payload); |
| JWT Token Structure | header.payload.signature (Base64-encoded) |
| Flask SSE Response | Response(generator(), mimetype="text/event-stream") |
this in Arrow Function | const obj = { val: 1, getVal: () => this.val }; → this = outer scope. |
| Vue Computed Property | computed: { fullName() { return this.first + this.last; } } |
| Fetch with Auth | fetch(url, { headers: { "Authorization": "Bearer token" } }) |
JavaScript:
this binding, promises, and array methods (reduce, map, filter).bind, call, and apply affect this.Vue.js:
computed (cached) and watch (side effects).state → mutations (synchronous) → actions (asynchronous).Authentication:
localStorage (persistent) or sessionStorage (session-only).Real-Time:
Flask:
Response with generators for SSE.@jwt_required() for protected routes.Debugging:
computed properties).vue-devtools for state inspection.